prefer-code-point.js 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. 'use strict';
  2. const {methodCallSelector} = require('./selectors/index.js');
  3. const messages = {
  4. 'error/charCodeAt': 'Prefer `String#codePointAt()` over `String#charCodeAt()`.',
  5. 'error/fromCharCode': 'Prefer `String.fromCodePoint()` over `String.fromCharCode()`.',
  6. 'suggestion/charCodeAt': 'Use `String#codePointAt()`.',
  7. 'suggestion/fromCharCode': 'Use `String.fromCodePoint()`.',
  8. };
  9. const cases = [
  10. {
  11. selector: methodCallSelector('charCodeAt'),
  12. replacement: 'codePointAt',
  13. },
  14. {
  15. selector: methodCallSelector({object: 'String', method: 'fromCharCode'}),
  16. replacement: 'fromCodePoint',
  17. },
  18. ];
  19. /** @param {import('eslint').Rule.RuleContext} context */
  20. const create = () => Object.fromEntries(
  21. cases.map(({selector, replacement}) => [
  22. selector,
  23. node => {
  24. const method = node.callee.property;
  25. const methodName = method.name;
  26. const fix = fixer => fixer.replaceText(method, replacement);
  27. return {
  28. node: method,
  29. messageId: `error/${methodName}`,
  30. suggest: [
  31. {
  32. messageId: `suggestion/${methodName}`,
  33. fix,
  34. },
  35. ],
  36. };
  37. },
  38. ]),
  39. );
  40. /** @type {import('eslint').Rule.RuleModule} */
  41. module.exports = {
  42. create,
  43. meta: {
  44. type: 'suggestion',
  45. docs: {
  46. description: 'Prefer `String#codePointAt(…)` over `String#charCodeAt(…)` and `String.fromCodePoint(…)` over `String.fromCharCode(…)`.',
  47. },
  48. hasSuggestions: true,
  49. messages,
  50. },
  51. };