require-number-to-fixed-digits-argument.js 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. 'use strict';
  2. const {methodCallSelector, not} = require('./selectors/index.js');
  3. const {appendArgument} = require('./fix/index.js');
  4. const MESSAGE_ID = 'require-number-to-fixed-digits-argument';
  5. const messages = {
  6. [MESSAGE_ID]: 'Missing the digits argument.',
  7. };
  8. const mathToFixed = [
  9. methodCallSelector({
  10. method: 'toFixed',
  11. argumentsLength: 0,
  12. }),
  13. not('[callee.object.type="NewExpression"]'),
  14. ].join('');
  15. /** @param {import('eslint').Rule.RuleContext} context */
  16. const create = context => {
  17. const sourceCode = context.getSourceCode();
  18. return {
  19. [mathToFixed](node) {
  20. const [
  21. openingParenthesis,
  22. closingParenthesis,
  23. ] = sourceCode.getLastTokens(node, 2);
  24. return {
  25. loc: {
  26. start: openingParenthesis.loc.start,
  27. end: closingParenthesis.loc.end,
  28. },
  29. messageId: MESSAGE_ID,
  30. /** @param {import('eslint').Rule.RuleFixer} fixer */
  31. fix: fixer => appendArgument(fixer, node, '0', sourceCode),
  32. };
  33. },
  34. };
  35. };
  36. /** @type {import('eslint').Rule.RuleModule} */
  37. module.exports = {
  38. create,
  39. meta: {
  40. type: 'suggestion',
  41. docs: {
  42. description: 'Enforce using the digits argument with `Number#toFixed()`.',
  43. },
  44. fixable: 'code',
  45. messages,
  46. },
  47. };