no-instanceof-array.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. 'use strict';
  2. const {checkVueTemplate} = require('./utils/rule.js');
  3. const {getParenthesizedRange} = require('./utils/parentheses.js');
  4. const {replaceNodeOrTokenAndSpacesBefore, fixSpaceAroundKeyword} = require('./fix/index.js');
  5. const isInstanceofToken = token => token.value === 'instanceof' && token.type === 'Keyword';
  6. const MESSAGE_ID = 'no-instanceof-array';
  7. const messages = {
  8. [MESSAGE_ID]: 'Use `Array.isArray()` instead of `instanceof Array`.',
  9. };
  10. const selector = [
  11. 'BinaryExpression',
  12. '[operator="instanceof"]',
  13. '[right.type="Identifier"]',
  14. '[right.name="Array"]',
  15. ].join('');
  16. /** @param {import('eslint').Rule.RuleContext} context */
  17. const create = context => {
  18. const sourceCode = context.getSourceCode();
  19. return {
  20. [selector](node) {
  21. const {left, right} = node;
  22. let tokenStore = sourceCode;
  23. let instanceofToken = tokenStore.getTokenAfter(left, isInstanceofToken);
  24. if (!instanceofToken && context.parserServices.getTemplateBodyTokenStore) {
  25. tokenStore = context.parserServices.getTemplateBodyTokenStore();
  26. instanceofToken = tokenStore.getTokenAfter(left, isInstanceofToken);
  27. }
  28. return {
  29. node: instanceofToken,
  30. messageId: MESSAGE_ID,
  31. /** @param {import('eslint').Rule.RuleFixer} fixer */
  32. * fix(fixer) {
  33. yield * fixSpaceAroundKeyword(fixer, node, sourceCode);
  34. const range = getParenthesizedRange(left, tokenStore);
  35. yield fixer.insertTextBeforeRange(range, 'Array.isArray(');
  36. yield fixer.insertTextAfterRange(range, ')');
  37. yield * replaceNodeOrTokenAndSpacesBefore(instanceofToken, '', fixer, sourceCode, tokenStore);
  38. yield * replaceNodeOrTokenAndSpacesBefore(right, '', fixer, sourceCode, tokenStore);
  39. },
  40. };
  41. },
  42. };
  43. };
  44. /** @type {import('eslint').Rule.RuleModule} */
  45. module.exports = {
  46. create: checkVueTemplate(create),
  47. meta: {
  48. type: 'suggestion',
  49. docs: {
  50. description: 'Require `Array.isArray()` instead of `instanceof Array`.',
  51. },
  52. fixable: 'code',
  53. messages,
  54. },
  55. };