Skip to content

Commit 45ffb22

Browse files
committed
Refactor
1 parent d62d840 commit 45ffb22

File tree

1 file changed

+15
-28
lines changed

1 file changed

+15
-28
lines changed

rules/no-zero-fractions.js

Lines changed: 15 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
'use strict';
22
const getDocumentationUrl = require('./utils/get-documentation-url');
3+
const {isNumber, parseNumber} = require('./utils/numeric');
34

45
const MESSAGE_ZERO_FRACTION = 'zero-fraction';
56
const MESSAGE_DANGLING_DOT = 'dangling-dot';
@@ -8,46 +9,32 @@ const messages = {
89
[MESSAGE_DANGLING_DOT]: 'Don\'t use a dangling dot in the number.'
910
};
1011

11-
// Groups:
12-
// 1. Integer part.
13-
// 2. Dangling dot or dot with zeroes.
14-
// 3. Dot with digits except last zeroes.
15-
// 4. Scientific notation.
16-
const RE_DANGLINGDOT_OR_ZERO_FRACTIONS = /^(?<integerPart>[+-]?\d*)(?:(?<dotAndZeroes>\.0*)|(?<dotAndDigits>\.\d*[1-9])0+)(?<scientificNotationSuffix>e[+-]?\d+)?$/;
12+
const format = text => {
13+
// Legacy octal number `0777` and prefixed number `0o1234` can't has dot.
14+
const {number, mark, sign, power} = parseNumber(text);
15+
return {
16+
hasDanglingDot: number.endsWith('.'),
17+
formatted: number.replace(/[0_.]$/g, '') + mark + sign + power
18+
};
19+
}
1720

1821
const create = context => {
1922
return {
2023
Literal: node => {
21-
if (typeof node.value !== 'number') {
24+
const {raw} = node;
25+
if (!isNumber(node) || !raw.includes('.')) {
2226
return;
2327
}
2428

25-
const match = RE_DANGLINGDOT_OR_ZERO_FRACTIONS.exec(node.raw);
26-
if (match === null) {
29+
const {hasDanglingDot, formatted} = format(raw);
30+
if (formatted === raw) {
2731
return;
2832
}
2933

30-
const {
31-
integerPart,
32-
dotAndZeroes,
33-
dotAndDigits,
34-
scientificNotationSuffix
35-
} = match.groups;
36-
37-
const isDanglingDot = dotAndZeroes === '.';
38-
3934
context.report({
4035
node,
41-
messageId: isDanglingDot ? MESSAGE_DANGLING_DOT : MESSAGE_ZERO_FRACTION,
42-
fix: fixer => {
43-
let wantedString = dotAndZeroes === undefined ? integerPart + dotAndDigits : integerPart;
44-
45-
if (scientificNotationSuffix !== undefined) {
46-
wantedString += scientificNotationSuffix;
47-
}
48-
49-
return fixer.replaceText(node, wantedString);
50-
}
36+
messageId: hasDanglingDot ? MESSAGE_DANGLING_DOT : MESSAGE_ZERO_FRACTION,
37+
fix: fixer => fixer.replaceText(node, formatted)
5138
});
5239
}
5340
};

0 commit comments

Comments
 (0)