no-new-wrappers.js 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. /**
  2. * @fileoverview Rule to flag when using constructor for wrapper objects
  3. * @author Ilya Volodin
  4. */
  5. "use strict";
  6. //------------------------------------------------------------------------------
  7. // Requirements
  8. //------------------------------------------------------------------------------
  9. const { getVariableByName } = require("./utils/ast-utils");
  10. //------------------------------------------------------------------------------
  11. // Rule Definition
  12. //------------------------------------------------------------------------------
  13. /** @type {import('../types').Rule.RuleModule} */
  14. module.exports = {
  15. meta: {
  16. type: "suggestion",
  17. docs: {
  18. description:
  19. "Disallow `new` operators with the `String`, `Number`, and `Boolean` objects",
  20. recommended: false,
  21. url: "https://eslint.org/docs/latest/rules/no-new-wrappers",
  22. },
  23. schema: [],
  24. messages: {
  25. noConstructor: "Do not use {{fn}} as a constructor.",
  26. },
  27. },
  28. create(context) {
  29. const { sourceCode } = context;
  30. return {
  31. NewExpression(node) {
  32. const wrapperObjects = ["String", "Number", "Boolean"];
  33. const { name } = node.callee;
  34. if (wrapperObjects.includes(name)) {
  35. const variable = getVariableByName(
  36. sourceCode.getScope(node),
  37. name,
  38. );
  39. if (variable && variable.identifiers.length === 0) {
  40. context.report({
  41. node,
  42. messageId: "noConstructor",
  43. data: { fn: name },
  44. });
  45. }
  46. }
  47. },
  48. };
  49. },
  50. };