generated from Nerdware-LLC/template-npm-pkg
-
Notifications
You must be signed in to change notification settings - Fork 0
/
safeJsonStringify.ts
33 lines (28 loc) 路 1.04 KB
/
safeJsonStringify.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import { isBigInt } from "./isBigInt.js";
import { isFunction } from "./isFunction.js";
import { isObjectLike } from "./isObjectLike.js";
/**
* This function is a safe version of `JSON.stringify` which will not throw
* an error if the input contains circular references or BigInts.
*/
export const safeJsonStringify: typeof JSON.stringify = (input: unknown, replacer, space) => {
const circularSet = new WeakSet<object>();
const customReplacer = (key: string, value: unknown) => {
const { stringified, shouldAddRef = false } = isBigInt(value)
? { stringified: `${value.toString()}n` }
: isObjectLike(value)
? circularSet.has(value)
? { stringified: "[Circular]" }
: { stringified: value, shouldAddRef: true }
: { stringified: value };
if (shouldAddRef) circularSet.add(value as object);
return stringified;
};
return JSON.stringify(
input,
isFunction(replacer)
? (key, val) => customReplacer(key, replacer(key, val)) // prettier-ignore
: customReplacer,
space
);
};