Skip to content

Commit

Permalink
Merge pull request #56 from JesusTheHun/feature/support-bigint
Browse files Browse the repository at this point in the history
Add support for BigInt
  • Loading branch information
gaetanmaisse authored May 13, 2021
2 parents add7d38 + 01648e7 commit 2339355
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 1 deletion.
8 changes: 8 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -161,6 +161,10 @@ export const replacer = function replacer(options: Options) {
return value;
}

if (typeof value === 'bigint') {
return `_bigint_${value.toString()}`;
}

if (typeof value === 'string') {
if (dateFormat.test(value)) {
if (!options.allowDate) {
Expand Down Expand Up @@ -348,6 +352,10 @@ export const reviver = function reviver(options: Options) {
return NaN;
}

if (typeof value === 'string' && value.startsWith('_bigint_') && typeof BigInt === 'function') {
return BigInt(value.replace('_bigint_', ''));
}

return value;
};
};
Expand Down
10 changes: 10 additions & 0 deletions test/common/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -230,6 +230,16 @@ const tests = ({ stringify, parse }) => {
expect(parsed).toMatchObject(data);
});

test('check BigInt value', () => {
const data = { LotOfFruits: BigInt('123456789123456789123456789123456789') };

const stringified = stringify(data);
const parsed = parse(stringified);

expect(stringified).toEqual('{"LotOfFruits":"_bigint_123456789123456789123456789123456789"}');
expect(parsed).toMatchObject(data);
});

test('check undefined value', () => {
const data = { undefinedFruit: undefined };

Expand Down
7 changes: 6 additions & 1 deletion tsconfig.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,12 @@
{
"compilerOptions": {
"target": "es5",
"lib": ["es2015", "es2017", "dom"],
"lib": [
"es2015",
"es2017",
"dom",
"es2020.bigint"
],
"module": "commonjs",
"declaration": true,
"removeComments": true,
Expand Down

0 comments on commit 2339355

Please sign in to comment.