int.js 2.2 KB

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