no-loss-of-precision.js 7.73 KB
Newer Older
Rosanny Sihombing's avatar
Rosanny Sihombing committed
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
/**
 * @fileoverview Rule to flag numbers that will lose significant figure precision at runtime
 * @author Jacob Moore
 */

"use strict";

//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------

module.exports = {
    meta: {
        type: "problem",

        docs: {
            description: "disallow literal numbers that lose precision",
            category: "Possible Errors",
            recommended: false,
            url: "https://eslint.org/docs/rules/no-loss-of-precision"
        },
        schema: [],
        messages: {
            noLossOfPrecision: "This number literal will lose precision at runtime."
        }
    },

    create(context) {

        /**
         * Returns whether the node is number literal
         * @param {Node} node the node literal being evaluated
         * @returns {boolean} true if the node is a number literal
         */
        function isNumber(node) {
            return typeof node.value === "number";
        }

        /**
         * Gets the source code of the given number literal. Removes `_` numeric separators from the result.
         * @param {Node} node the number `Literal` node
         * @returns {string} raw source code of the literal, without numeric separators
         */
        function getRaw(node) {
            return node.raw.replace(/_/gu, "");
        }

        /**
         * Checks whether the number is  base ten
         * @param {ASTNode} node the node being evaluated
         * @returns {boolean} true if the node is in base ten
         */
        function isBaseTen(node) {
            const prefixes = ["0x", "0X", "0b", "0B", "0o", "0O"];

            return prefixes.every(prefix => !node.raw.startsWith(prefix)) &&
            !/^0[0-7]+$/u.test(node.raw);
        }

        /**
         * Checks that the user-intended non-base ten number equals the actual number after is has been converted to the Number type
         * @param {Node} node the node being evaluated
         * @returns {boolean} true if they do not match
         */
        function notBaseTenLosesPrecision(node) {
            const rawString = getRaw(node).toUpperCase();
            let base = 0;

            if (rawString.startsWith("0B")) {
                base = 2;
            } else if (rawString.startsWith("0X")) {
                base = 16;
            } else {
                base = 8;
            }

            return !rawString.endsWith(node.value.toString(base).toUpperCase());
        }

        /**
         * Adds a decimal point to the numeric string at index 1
         * @param {string} stringNumber the numeric string without any decimal point
         * @returns {string} the numeric string with a decimal point in the proper place
         */
        function addDecimalPointToNumber(stringNumber) {
            return `${stringNumber.slice(0, 1)}.${stringNumber.slice(1)}`;
        }

        /**
         * Returns the number stripped of leading zeros
         * @param {string} numberAsString the string representation of the number
         * @returns {string} the stripped string
         */
        function removeLeadingZeros(numberAsString) {
            return numberAsString.replace(/^0*/u, "");
        }

        /**
         * Returns the number stripped of trailing zeros
         * @param {string} numberAsString the string representation of the number
         * @returns {string} the stripped string
         */
        function removeTrailingZeros(numberAsString) {
            return numberAsString.replace(/0*$/u, "");
        }

        /**
         * Converts an integer to to an object containing the integer's coefficient and order of magnitude
         * @param {string} stringInteger the string representation of the integer being converted
         * @returns {Object} the object containing the integer's coefficient and order of magnitude
         */
        function normalizeInteger(stringInteger) {
            const significantDigits = removeTrailingZeros(removeLeadingZeros(stringInteger));

            return {
                magnitude: stringInteger.startsWith("0") ? stringInteger.length - 2 : stringInteger.length - 1,
                coefficient: addDecimalPointToNumber(significantDigits)
            };
        }

        /**
         *
         * Converts a float to to an object containing the floats's coefficient and order of magnitude
         * @param {string} stringFloat the string representation of the float being converted
         * @returns {Object} the object containing the integer's coefficient and order of magnitude
         */
        function normalizeFloat(stringFloat) {
            const trimmedFloat = removeLeadingZeros(stringFloat);

            if (trimmedFloat.startsWith(".")) {
                const decimalDigits = trimmedFloat.split(".").pop();
                const significantDigits = removeLeadingZeros(decimalDigits);

                return {
                    magnitude: significantDigits.length - decimalDigits.length - 1,
                    coefficient: addDecimalPointToNumber(significantDigits)
                };

            }
            return {
                magnitude: trimmedFloat.indexOf(".") - 1,
                coefficient: addDecimalPointToNumber(trimmedFloat.replace(".", ""))

            };
        }


        /**
         * Converts a base ten number to proper scientific notation
         * @param {string} stringNumber the string representation of the base ten number to be converted
         * @returns {string} the number converted to scientific notation
         */
        function convertNumberToScientificNotation(stringNumber) {
            const splitNumber = stringNumber.replace("E", "e").split("e");
            const originalCoefficient = splitNumber[0];
            const normalizedNumber = stringNumber.includes(".") ? normalizeFloat(originalCoefficient)
                : normalizeInteger(originalCoefficient);
            const normalizedCoefficient = normalizedNumber.coefficient;
            const magnitude = splitNumber.length > 1 ? (parseInt(splitNumber[1], 10) + normalizedNumber.magnitude)
                : normalizedNumber.magnitude;

            return `${normalizedCoefficient}e${magnitude}`;

        }

        /**
         * Checks that the user-intended base ten number equals the actual number after is has been converted to the Number type
         * @param {Node} node the node being evaluated
         * @returns {boolean} true if they do not match
         */
        function baseTenLosesPrecision(node) {
            const normalizedRawNumber = convertNumberToScientificNotation(getRaw(node));
            const requestedPrecision = normalizedRawNumber.split("e")[0].replace(".", "").length;

            if (requestedPrecision > 100) {
                return true;
            }
            const storedNumber = node.value.toPrecision(requestedPrecision);
            const normalizedStoredNumber = convertNumberToScientificNotation(storedNumber);

            return normalizedRawNumber !== normalizedStoredNumber;
        }


        /**
         * Checks that the user-intended number equals the actual number after is has been converted to the Number type
         * @param {Node} node the node being evaluated
         * @returns {boolean} true if they do not match
         */
        function losesPrecision(node) {
            return isBaseTen(node) ? baseTenLosesPrecision(node) : notBaseTenLosesPrecision(node);
        }


        return {
            Literal(node) {
                if (node.value && isNumber(node) && losesPrecision(node)) {
                    context.report({
                        messageId: "noLossOfPrecision",
                        node
                    });
                }
            }
        };
    }
};