default-param-last.js 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. /**
  2. * @fileoverview enforce default parameters to be last
  3. * @author Chiawen Chen
  4. */
  5. "use strict";
  6. /** @type {import('../shared/types').Rule} */
  7. module.exports = {
  8. meta: {
  9. type: "suggestion",
  10. docs: {
  11. description: "Enforce default parameters to be last",
  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. /**
  22. * Handler for function contexts.
  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. };