int.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. 'use strict';
  2. var stringifyNumber = require('../../stringify/stringifyNumber.js');
  3. const intIdentify = (value) => typeof value === 'bigint' || Number.isInteger(value);
  4. const intResolve = (str, offset, radix, { intAsBigInt }) => (intAsBigInt ? BigInt(str) : parseInt(str.substring(offset), radix));
  5. function intStringify(node, radix, prefix) {
  6. const { value } = node;
  7. if (intIdentify(value) && value >= 0)
  8. return prefix + value.toString(radix);
  9. return stringifyNumber.stringifyNumber(node);
  10. }
  11. const intOct = {
  12. identify: value => intIdentify(value) && value >= 0,
  13. default: true,
  14. tag: 'tag:yaml.org,2002:int',
  15. format: 'OCT',
  16. test: /^0o[0-7]+$/,
  17. resolve: (str, _onError, opt) => intResolve(str, 2, 8, opt),
  18. stringify: node => intStringify(node, 8, '0o')
  19. };
  20. const int = {
  21. identify: intIdentify,
  22. default: true,
  23. tag: 'tag:yaml.org,2002:int',
  24. test: /^[-+]?[0-9]+$/,
  25. resolve: (str, _onError, opt) => intResolve(str, 0, 10, opt),
  26. stringify: stringifyNumber.stringifyNumber
  27. };
  28. const intHex = {
  29. identify: value => intIdentify(value) && value >= 0,
  30. default: true,
  31. tag: 'tag:yaml.org,2002:int',
  32. format: 'HEX',
  33. test: /^0x[0-9a-fA-F]+$/,
  34. resolve: (str, _onError, opt) => intResolve(str, 2, 16, opt),
  35. stringify: node => intStringify(node, 16, '0x')
  36. };
  37. exports.int = int;
  38. exports.intHex = intHex;
  39. exports.intOct = intOct;