UNPKG

1.47 kBJavaScriptView Raw
1'use strict';
2const getDocumentationUrl = require('./utils/get-documentation-url');
3
4const MESSAGE_ZERO_FRACTION = 'Don\'t use a zero fraction in the number.';
5const MESSAGE_DANGLING_DOT = 'Don\'t use a dangling dot in the number.';
6
7// Groups:
8// 1. Integer part.
9// 2. Dangling dot or dot with zeroes.
10// 3. Dot with digits except last zeroes.
11// 4. Scientific notation.
12const RE_DANGLINGDOT_OR_ZERO_FRACTIONS = /^(?<integerPart>[+-]?\d*)(?:(?<dotAndZeroes>\.0*)|(?<dotAndDigits>\.\d*[1-9])0+)(?<scientificNotationSuffix>e[+-]?\d+)?$/;
13
14const create = context => {
15 return {
16 Literal: node => {
17 if (typeof node.value !== 'number') {
18 return;
19 }
20
21 const match = RE_DANGLINGDOT_OR_ZERO_FRACTIONS.exec(node.raw);
22 if (match === null) {
23 return;
24 }
25
26 const {
27 integerPart,
28 dotAndZeroes,
29 dotAndDigits,
30 scientificNotationSuffix
31 } = match.groups;
32
33 const isDanglingDot = dotAndZeroes === '.';
34
35 context.report({
36 node,
37 message: isDanglingDot ? MESSAGE_DANGLING_DOT : MESSAGE_ZERO_FRACTION,
38 fix: fixer => {
39 let wantedString = dotAndZeroes === undefined ? integerPart + dotAndDigits : integerPart;
40
41 if (scientificNotationSuffix !== undefined) {
42 wantedString += scientificNotationSuffix;
43 }
44
45 return fixer.replaceText(node, wantedString);
46 }
47 });
48 }
49 };
50};
51
52module.exports = {
53 create,
54 meta: {
55 type: 'suggestion',
56 docs: {
57 url: getDocumentationUrl(__filename)
58 },
59 fixable: 'code'
60 }
61};