int.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. import { stringifyNumber } from '../../stringify/stringifyNumber.js';
  2. const intIdentify = (value) => typeof value === 'bigint' || Number.isInteger(value);
  3. function intResolve(str, offset, radix, { intAsBigInt }) {
  4. const sign = str[0];
  5. if (sign === '-' || sign === '+')
  6. offset += 1;
  7. str = str.substring(offset).replace(/_/g, '');
  8. if (intAsBigInt) {
  9. switch (radix) {
  10. case 2:
  11. str = `0b${str}`;
  12. break;
  13. case 8:
  14. str = `0o${str}`;
  15. break;
  16. case 16:
  17. str = `0x${str}`;
  18. break;
  19. }
  20. const n = BigInt(str);
  21. return sign === '-' ? BigInt(-1) * n : n;
  22. }
  23. const n = parseInt(str, radix);
  24. return sign === '-' ? -1 * n : n;
  25. }
  26. function intStringify(node, radix, prefix) {
  27. const { value } = node;
  28. if (intIdentify(value)) {
  29. const str = value.toString(radix);
  30. return value < 0 ? '-' + prefix + str.substr(1) : prefix + str;
  31. }
  32. return stringifyNumber(node);
  33. }
  34. const intBin = {
  35. identify: intIdentify,
  36. default: true,
  37. tag: 'tag:yaml.org,2002:int',
  38. format: 'BIN',
  39. test: /^[-+]?0b[0-1_]+$/,
  40. resolve: (str, _onError, opt) => intResolve(str, 2, 2, opt),
  41. stringify: node => intStringify(node, 2, '0b')
  42. };
  43. const intOct = {
  44. identify: intIdentify,
  45. default: true,
  46. tag: 'tag:yaml.org,2002:int',
  47. format: 'OCT',
  48. test: /^[-+]?0[0-7_]+$/,
  49. resolve: (str, _onError, opt) => intResolve(str, 1, 8, opt),
  50. stringify: node => intStringify(node, 8, '0')
  51. };
  52. const int = {
  53. identify: intIdentify,
  54. default: true,
  55. tag: 'tag:yaml.org,2002:int',
  56. test: /^[-+]?[0-9][0-9_]*$/,
  57. resolve: (str, _onError, opt) => intResolve(str, 0, 10, opt),
  58. stringify: stringifyNumber
  59. };
  60. const intHex = {
  61. identify: intIdentify,
  62. default: true,
  63. tag: 'tag:yaml.org,2002:int',
  64. format: 'HEX',
  65. test: /^[-+]?0x[0-9a-fA-F_]+$/,
  66. resolve: (str, _onError, opt) => intResolve(str, 2, 16, opt),
  67. stringify: node => intStringify(node, 16, '0x')
  68. };
  69. export { int, intBin, intHex, intOct };