MCPcopy Create free account
hub / github.com/dipscope/TypeManager.TS / jsonStringify

Function jsonStringify

src/functions/json-stringify.ts:10–113  ·  view source on GitHub ↗
(
    x: any,
    replacer?: (this: any, key: string, value: any) => any | Array<number> | Array<string> | null,
    space?: string | number
)

Source from the content-addressed store, hash-verified

8 * @returns {string} Consistent JSON string which can be used for hashing.
9 */
10export function jsonStringify(
11 x: any,
12 replacer?: (this: any, key: string, value: any) => any | Array<number> | Array<string> | null,
13 space?: string | number
14): string
15{
16 const spacing = typeof space === 'number' ? new Array(isFinite(space) ? space + 1 : 0).join(' ') : (space ?? '');
17 const separator = spacing ? ': ' : ':';
18 const seen = new Set<any>();
19 const indents = [''];
20
21 const indentify = (level: number): string =>
22 {
23 while (indents.length <= level)
24 {
25 indents.push(indents[indents.length - 1] + spacing);
26 }
27
28 return indents[level];
29 };
30
31 const stringify = (parent: any, key: string, node: any, level: number): string =>
32 {
33 if (node && node.toJSON && typeof node.toJSON === 'function')
34 {
35 node = node.toJSON();
36 }
37
38 if (replacer)
39 {
40 node = replacer.call(parent, key, node);
41 }
42
43 if (node === undefined)
44 {
45 return '';
46 }
47
48 if (node === null)
49 {
50 return 'null';
51 }
52
53 if (typeof node === 'number')
54 {
55 return isFinite(node) ? String(node) : 'null';
56 }
57
58 if (typeof node !== 'object')
59 {
60 return JSON.stringify(node);
61 }
62
63 if (seen.has(node))
64 {
65 return 'null';
66 }
67

Callers 1

stringifyMethod · 0.90

Calls 1

stringifyFunction · 0.85

Tested by

no test coverage detected