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