numeric.js 1.4 KB

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