no-loss-of-precision.js 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  1. /**
  2. * @fileoverview Rule to flag numbers that will lose significant figure precision at runtime
  3. * @author Jacob Moore
  4. */
  5. "use strict";
  6. //------------------------------------------------------------------------------
  7. // Rule Definition
  8. //------------------------------------------------------------------------------
  9. module.exports = {
  10. meta: {
  11. type: "problem",
  12. docs: {
  13. description: "disallow literal numbers that lose precision",
  14. category: "Possible Errors",
  15. recommended: false,
  16. url: "https://eslint.org/docs/rules/no-loss-of-precision"
  17. },
  18. schema: [],
  19. messages: {
  20. noLossOfPrecision: "This number literal will lose precision at runtime."
  21. }
  22. },
  23. create(context) {
  24. /**
  25. * Returns whether the node is number literal
  26. * @param {Node} node the node literal being evaluated
  27. * @returns {boolean} true if the node is a number literal
  28. */
  29. function isNumber(node) {
  30. return typeof node.value === "number";
  31. }
  32. /**
  33. * Gets the source code of the given number literal. Removes `_` numeric separators from the result.
  34. * @param {Node} node the number `Literal` node
  35. * @returns {string} raw source code of the literal, without numeric separators
  36. */
  37. function getRaw(node) {
  38. return node.raw.replace(/_/gu, "");
  39. }
  40. /**
  41. * Checks whether the number is base ten
  42. * @param {ASTNode} node the node being evaluated
  43. * @returns {boolean} true if the node is in base ten
  44. */
  45. function isBaseTen(node) {
  46. const prefixes = ["0x", "0X", "0b", "0B", "0o", "0O"];
  47. return prefixes.every(prefix => !node.raw.startsWith(prefix)) &&
  48. !/^0[0-7]+$/u.test(node.raw);
  49. }
  50. /**
  51. * Checks that the user-intended non-base ten number equals the actual number after is has been converted to the Number type
  52. * @param {Node} node the node being evaluated
  53. * @returns {boolean} true if they do not match
  54. */
  55. function notBaseTenLosesPrecision(node) {
  56. const rawString = getRaw(node).toUpperCase();
  57. let base = 0;
  58. if (rawString.startsWith("0B")) {
  59. base = 2;
  60. } else if (rawString.startsWith("0X")) {
  61. base = 16;
  62. } else {
  63. base = 8;
  64. }
  65. return !rawString.endsWith(node.value.toString(base).toUpperCase());
  66. }
  67. /**
  68. * Adds a decimal point to the numeric string at index 1
  69. * @param {string} stringNumber the numeric string without any decimal point
  70. * @returns {string} the numeric string with a decimal point in the proper place
  71. */
  72. function addDecimalPointToNumber(stringNumber) {
  73. return `${stringNumber.slice(0, 1)}.${stringNumber.slice(1)}`;
  74. }
  75. /**
  76. * Returns the number stripped of leading zeros
  77. * @param {string} numberAsString the string representation of the number
  78. * @returns {string} the stripped string
  79. */
  80. function removeLeadingZeros(numberAsString) {
  81. return numberAsString.replace(/^0*/u, "");
  82. }
  83. /**
  84. * Returns the number stripped of trailing zeros
  85. * @param {string} numberAsString the string representation of the number
  86. * @returns {string} the stripped string
  87. */
  88. function removeTrailingZeros(numberAsString) {
  89. return numberAsString.replace(/0*$/u, "");
  90. }
  91. /**
  92. * Converts an integer to to an object containing the the integer's coefficient and order of magnitude
  93. * @param {string} stringInteger the string representation of the integer being converted
  94. * @returns {Object} the object containing the the integer's coefficient and order of magnitude
  95. */
  96. function normalizeInteger(stringInteger) {
  97. const significantDigits = removeTrailingZeros(removeLeadingZeros(stringInteger));
  98. return {
  99. magnitude: stringInteger.startsWith("0") ? stringInteger.length - 2 : stringInteger.length - 1,
  100. coefficient: addDecimalPointToNumber(significantDigits)
  101. };
  102. }
  103. /**
  104. *
  105. * Converts a float to to an object containing the the floats's coefficient and order of magnitude
  106. * @param {string} stringFloat the string representation of the float being converted
  107. * @returns {Object} the object containing the the integer's coefficient and order of magnitude
  108. */
  109. function normalizeFloat(stringFloat) {
  110. const trimmedFloat = removeLeadingZeros(stringFloat);
  111. if (trimmedFloat.startsWith(".")) {
  112. const decimalDigits = trimmedFloat.split(".").pop();
  113. const significantDigits = removeLeadingZeros(decimalDigits);
  114. return {
  115. magnitude: significantDigits.length - decimalDigits.length - 1,
  116. coefficient: addDecimalPointToNumber(significantDigits)
  117. };
  118. }
  119. return {
  120. magnitude: trimmedFloat.indexOf(".") - 1,
  121. coefficient: addDecimalPointToNumber(trimmedFloat.replace(".", ""))
  122. };
  123. }
  124. /**
  125. * Converts a base ten number to proper scientific notation
  126. * @param {string} stringNumber the string representation of the base ten number to be converted
  127. * @returns {string} the number converted to scientific notation
  128. */
  129. function convertNumberToScientificNotation(stringNumber) {
  130. const splitNumber = stringNumber.replace("E", "e").split("e");
  131. const originalCoefficient = splitNumber[0];
  132. const normalizedNumber = stringNumber.includes(".") ? normalizeFloat(originalCoefficient)
  133. : normalizeInteger(originalCoefficient);
  134. const normalizedCoefficient = normalizedNumber.coefficient;
  135. const magnitude = splitNumber.length > 1 ? (parseInt(splitNumber[1], 10) + normalizedNumber.magnitude)
  136. : normalizedNumber.magnitude;
  137. return `${normalizedCoefficient}e${magnitude}`;
  138. }
  139. /**
  140. * Checks that the user-intended base ten number equals the actual number after is has been converted to the Number type
  141. * @param {Node} node the node being evaluated
  142. * @returns {boolean} true if they do not match
  143. */
  144. function baseTenLosesPrecision(node) {
  145. const normalizedRawNumber = convertNumberToScientificNotation(getRaw(node));
  146. const requestedPrecision = normalizedRawNumber.split("e")[0].replace(".", "").length;
  147. if (requestedPrecision > 100) {
  148. return true;
  149. }
  150. const storedNumber = node.value.toPrecision(requestedPrecision);
  151. const normalizedStoredNumber = convertNumberToScientificNotation(storedNumber);
  152. return normalizedRawNumber !== normalizedStoredNumber;
  153. }
  154. /**
  155. * Checks that the user-intended number equals the actual number after is has been converted to the Number type
  156. * @param {Node} node the node being evaluated
  157. * @returns {boolean} true if they do not match
  158. */
  159. function losesPrecision(node) {
  160. return isBaseTen(node) ? baseTenLosesPrecision(node) : notBaseTenLosesPrecision(node);
  161. }
  162. return {
  163. Literal(node) {
  164. if (node.value && isNumber(node) && losesPrecision(node)) {
  165. context.report({
  166. messageId: "noLossOfPrecision",
  167. node
  168. });
  169. }
  170. }
  171. };
  172. }
  173. };