eslint-local-rules.js 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. "use strict";
  2. function getPrototypeMethods(prototype) {
  3. /* eslint-disable local-rules/no-prototype-methods */
  4. return Object.getOwnPropertyNames(prototype).filter(function(name) {
  5. return (
  6. typeof prototype[name] === "function" &&
  7. prototype.hasOwnProperty(name)
  8. );
  9. });
  10. }
  11. var DISALLOWED_ARRAY_PROPS = getPrototypeMethods(Array.prototype);
  12. var DISALLOWED_OBJECT_PROPS = getPrototypeMethods(Object.prototype);
  13. module.exports = {
  14. // rule to disallow direct use of prototype methods of builtins
  15. "no-prototype-methods": {
  16. meta: {
  17. docs: {
  18. description: "disallow calling prototype methods directly",
  19. category: "Possible Errors",
  20. recommended: false,
  21. url: "https://eslint.org/docs/rules/no-prototype-builtins"
  22. },
  23. schema: []
  24. },
  25. create: function(context) {
  26. /**
  27. * Reports if a disallowed property is used in a CallExpression
  28. * @param {ASTNode} node The CallExpression node.
  29. * @returns {void}
  30. */
  31. function disallowBuiltIns(node) {
  32. if (
  33. node.callee.type !== "MemberExpression" ||
  34. node.callee.computed ||
  35. // allow static method calls
  36. node.callee.object.name === "Array" ||
  37. node.callee.object.name === "Object"
  38. ) {
  39. return;
  40. }
  41. var propName = node.callee.property.name;
  42. if (DISALLOWED_OBJECT_PROPS.indexOf(propName) > -1) {
  43. context.report({
  44. message:
  45. "Do not access {{obj}} prototype method '{{prop}}' from target object.",
  46. loc: node.callee.property.loc.start,
  47. data: {
  48. obj: "Object",
  49. prop: propName
  50. },
  51. node: node
  52. });
  53. } else if (DISALLOWED_ARRAY_PROPS.indexOf(propName) > -1) {
  54. context.report({
  55. message:
  56. "Do not access {{obj}} prototype method '{{prop}}' from target object.",
  57. loc: node.callee.property.loc.start,
  58. data: {
  59. obj: "Array",
  60. prop: propName
  61. },
  62. node: node
  63. });
  64. }
  65. }
  66. return {
  67. CallExpression: disallowBuiltIns
  68. };
  69. }
  70. }
  71. };