no-floating-decimal.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. /**
  2. * @fileoverview Rule to flag use of a leading/trailing decimal point in a numeric literal
  3. * @author James Allardice
  4. */
  5. "use strict";
  6. //------------------------------------------------------------------------------
  7. // Requirements
  8. //------------------------------------------------------------------------------
  9. const astUtils = require("./utils/ast-utils");
  10. //------------------------------------------------------------------------------
  11. // Rule Definition
  12. //------------------------------------------------------------------------------
  13. /** @type {import('../shared/types').Rule} */
  14. module.exports = {
  15. meta: {
  16. type: "suggestion",
  17. docs: {
  18. description: "Disallow leading or trailing decimal points in numeric literals",
  19. recommended: false,
  20. url: "https://eslint.org/docs/rules/no-floating-decimal"
  21. },
  22. schema: [],
  23. fixable: "code",
  24. messages: {
  25. leading: "A leading decimal point can be confused with a dot.",
  26. trailing: "A trailing decimal point can be confused with a dot."
  27. }
  28. },
  29. create(context) {
  30. const sourceCode = context.getSourceCode();
  31. return {
  32. Literal(node) {
  33. if (typeof node.value === "number") {
  34. if (node.raw.startsWith(".")) {
  35. context.report({
  36. node,
  37. messageId: "leading",
  38. fix(fixer) {
  39. const tokenBefore = sourceCode.getTokenBefore(node);
  40. const needsSpaceBefore = tokenBefore &&
  41. tokenBefore.range[1] === node.range[0] &&
  42. !astUtils.canTokensBeAdjacent(tokenBefore, `0${node.raw}`);
  43. return fixer.insertTextBefore(node, needsSpaceBefore ? " 0" : "0");
  44. }
  45. });
  46. }
  47. if (node.raw.indexOf(".") === node.raw.length - 1) {
  48. context.report({
  49. node,
  50. messageId: "trailing",
  51. fix: fixer => fixer.insertTextAfter(node, "0")
  52. });
  53. }
  54. }
  55. }
  56. };
  57. }
  58. };