-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
41 lines (41 loc) · 1.26 KB
/
index.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
34
35
36
37
38
39
40
41
/**
* Safely converts an object to a JSON string representation.
*
* @param replacerFunction - Optional function to customize the transformation of values.
* @param indentation - Optional string or number specifying the indentation level.
* @param object - The object to be converted to JSON.
* @returns The JSON string representation of the object, or undefined if an error occurs.
* @throws Error if unable to stringify the object.
*/
export function safeJSON({
replacerFunction,
indentation,
object,
}: {
replacerFunction?: (key: string, value: unknown) => unknown;
indentation?: string | number;
object: unknown;
}): string | undefined {
try {
const visitedObjects = new Set<object>();
const jsonString = JSON.stringify(
object,
function (key, value) {
if (typeof value === "object" && value !== null) {
if (visitedObjects.has(value)) {
return "[Circular]";
}
visitedObjects.add(value);
}
return replacerFunction ? replacerFunction(key, value) : value;
},
indentation,
);
visitedObjects.clear();
return jsonString;
} catch (error) {
if (error instanceof TypeError) {
throw new Error(`Unable to stringify object: ${error.message}`);
}
}
}