UNPKG

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