default-param-last.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. /**
  2. * @fileoverview enforce default parameters to be last
  3. * @author Chiawen Chen
  4. */
  5. "use strict";
  6. module.exports = {
  7. meta: {
  8. type: "suggestion",
  9. docs: {
  10. description: "enforce default parameters to be last",
  11. category: "Best Practices",
  12. recommended: false,
  13. url: "https://eslint.org/docs/rules/default-param-last"
  14. },
  15. schema: [],
  16. messages: {
  17. shouldBeLast: "Default parameters should be last."
  18. }
  19. },
  20. create(context) {
  21. // eslint-disable-next-line jsdoc/require-description
  22. /**
  23. * @param {ASTNode} node function node
  24. * @returns {void}
  25. */
  26. function handleFunction(node) {
  27. let hasSeenPlainParam = false;
  28. for (let i = node.params.length - 1; i >= 0; i -= 1) {
  29. const param = node.params[i];
  30. if (
  31. param.type !== "AssignmentPattern" &&
  32. param.type !== "RestElement"
  33. ) {
  34. hasSeenPlainParam = true;
  35. continue;
  36. }
  37. if (hasSeenPlainParam && param.type === "AssignmentPattern") {
  38. context.report({
  39. node: param,
  40. messageId: "shouldBeLast"
  41. });
  42. }
  43. }
  44. }
  45. return {
  46. FunctionDeclaration: handleFunction,
  47. FunctionExpression: handleFunction,
  48. ArrowFunctionExpression: handleFunction
  49. };
  50. }
  51. };