25'ten fazla konu seçemezsiniz Konular bir harf veya rakamla başlamalı, kısa çizgiler ('-') içerebilir ve en fazla 35 karakter uzunluğunda olabilir.
 
 
 
 

95 satır
2.8 KiB

  1. /**
  2. * @fileoverview Rule to enforce a particular function style
  3. * @author Nicholas C. Zakas
  4. */
  5. "use strict";
  6. //------------------------------------------------------------------------------
  7. // Rule Definition
  8. //------------------------------------------------------------------------------
  9. module.exports = {
  10. meta: {
  11. docs: {
  12. description: "enforce the consistent use of either `function` declarations or expressions",
  13. category: "Stylistic Issues",
  14. recommended: false,
  15. url: "https://eslint.org/docs/rules/func-style"
  16. },
  17. schema: [
  18. {
  19. enum: ["declaration", "expression"]
  20. },
  21. {
  22. type: "object",
  23. properties: {
  24. allowArrowFunctions: {
  25. type: "boolean"
  26. }
  27. },
  28. additionalProperties: false
  29. }
  30. ],
  31. messages: {
  32. expression: "Expected a function expression.",
  33. declaration: "Expected a function declaration."
  34. }
  35. },
  36. create(context) {
  37. const style = context.options[0],
  38. allowArrowFunctions = context.options[1] && context.options[1].allowArrowFunctions === true,
  39. enforceDeclarations = (style === "declaration"),
  40. stack = [];
  41. const nodesToCheck = {
  42. FunctionDeclaration(node) {
  43. stack.push(false);
  44. if (!enforceDeclarations && node.parent.type !== "ExportDefaultDeclaration") {
  45. context.report({ node, messageId: "expression" });
  46. }
  47. },
  48. "FunctionDeclaration:exit"() {
  49. stack.pop();
  50. },
  51. FunctionExpression(node) {
  52. stack.push(false);
  53. if (enforceDeclarations && node.parent.type === "VariableDeclarator") {
  54. context.report({ node: node.parent, messageId: "declaration" });
  55. }
  56. },
  57. "FunctionExpression:exit"() {
  58. stack.pop();
  59. },
  60. ThisExpression() {
  61. if (stack.length > 0) {
  62. stack[stack.length - 1] = true;
  63. }
  64. }
  65. };
  66. if (!allowArrowFunctions) {
  67. nodesToCheck.ArrowFunctionExpression = function() {
  68. stack.push(false);
  69. };
  70. nodesToCheck["ArrowFunctionExpression:exit"] = function(node) {
  71. const hasThisExpr = stack.pop();
  72. if (enforceDeclarations && !hasThisExpr && node.parent.type === "VariableDeclarator") {
  73. context.report({ node: node.parent, messageId: "declaration" });
  74. }
  75. };
  76. }
  77. return nodesToCheck;
  78. }
  79. };