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