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