require-array-join-separator.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. 'use strict';
  2. const {matches, methodCallSelector, arrayPrototypeMethodSelector} = require('./selectors/index.js');
  3. const {appendArgument} = require('./fix/index.js');
  4. const MESSAGE_ID = 'require-array-join-separator';
  5. const messages = {
  6. [MESSAGE_ID]: 'Missing the separator argument.',
  7. };
  8. const selector = matches([
  9. // `foo.join()`
  10. methodCallSelector({
  11. method: 'join',
  12. argumentsLength: 0,
  13. includeOptionalMember: true,
  14. }),
  15. // `[].join.call(foo)` and `Array.prototype.join.call(foo)`
  16. [
  17. methodCallSelector({method: 'call', argumentsLength: 1}),
  18. arrayPrototypeMethodSelector({path: 'callee.object', method: 'join'}),
  19. ].join(''),
  20. ]);
  21. /** @param {import('eslint').Rule.RuleContext} context */
  22. const create = context => {
  23. const sourceCode = context.getSourceCode();
  24. return {
  25. [selector](node) {
  26. const [penultimateToken, lastToken] = sourceCode.getLastTokens(node, 2);
  27. const isPrototypeMethod = node.arguments.length === 1;
  28. return {
  29. loc: {
  30. start: penultimateToken.loc[isPrototypeMethod ? 'end' : 'start'],
  31. end: lastToken.loc.end,
  32. },
  33. messageId: MESSAGE_ID,
  34. /** @param {import('eslint').Rule.RuleFixer} fixer */
  35. fix: fixer => appendArgument(fixer, node, '\',\'', sourceCode),
  36. };
  37. },
  38. };
  39. };
  40. /** @type {import('eslint').Rule.RuleModule} */
  41. module.exports = {
  42. create,
  43. meta: {
  44. type: 'suggestion',
  45. docs: {
  46. description: 'Enforce using the separator argument with `Array#join()`.',
  47. },
  48. fixable: 'code',
  49. messages,
  50. },
  51. };