numeric.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. 'use strict';
  2. // Determine whether this node is a decimal integer literal.
  3. // Copied from https://github.com/eslint/eslint/blob/cc4871369645c3409dc56ded7a555af8a9f63d51/lib/rules/utils/ast-utils.js#L1237
  4. const DECIMAL_INTEGER_PATTERN = /^(?:0|0[0-7]*[89]\d*|[1-9](?:_?\d)*)$/u;
  5. const isDecimalInteger = text => DECIMAL_INTEGER_PATTERN.test(text);
  6. const isDecimalIntegerNode = node => isNumber(node) && isDecimalInteger(node.raw);
  7. const isNumber = node => typeof node.value === 'number';
  8. const isBigInt = node => Boolean(node.bigint);
  9. const isNumeric = node => isNumber(node) || isBigInt(node);
  10. const isLegacyOctal = node => isNumber(node) && /^0\d+$/.test(node.raw);
  11. function getPrefix(text) {
  12. let prefix = '';
  13. let data = text;
  14. if (/^0[box]/i.test(text)) {
  15. prefix = text.slice(0, 2);
  16. data = text.slice(2);
  17. }
  18. return {prefix, data};
  19. }
  20. function parseNumber(text) {
  21. const {
  22. number,
  23. mark = '',
  24. sign = '',
  25. power = '',
  26. } = text.match(/^(?<number>[\d._]*?)(?:(?<mark>[Ee])(?<sign>[+-])?(?<power>[\d_]+))?$/).groups;
  27. return {number, mark, sign, power};
  28. }
  29. function parseFloatNumber(text) {
  30. const parts = text.split('.');
  31. const [integer, fractional = ''] = parts;
  32. const dot = parts.length === 2 ? '.' : '';
  33. return {integer, dot, fractional};
  34. }
  35. module.exports = {
  36. isDecimalIntegerNode,
  37. isDecimalInteger,
  38. isNumber,
  39. isBigInt,
  40. isNumeric,
  41. isLegacyOctal,
  42. getPrefix,
  43. parseNumber,
  44. parseFloatNumber,
  45. };