MCPcopy Create free account
hub / github.com/sveltejs/devalue / flatten

Function flatten

src/stringify.js:99–380  ·  view source on GitHub ↗

* @param {any} thing * @param {number} [index]

(thing, index)

Source from the content-addressed store, hash-verified

97 * @param {number} [index]
98 */
99 function flatten(thing, index) {
100 if (thing === undefined) return UNDEFINED;
101 if (Number.isNaN(thing)) return NAN;
102 if (thing === Infinity) return POSITIVE_INFINITY;
103 if (thing === -Infinity) return NEGATIVE_INFINITY;
104 if (thing === 0 && 1 / thing < 0) return NEGATIVE_ZERO;
105
106 if (indexes.has(thing)) return /** @type {number} */ (indexes.get(thing));
107
108 index ??= p++;
109 indexes.set(thing, index);
110
111 for (const { key, fn } of custom) {
112 const value = fn(thing);
113 if (value) {
114 stringified[index] = `["${key}",${flatten(value)}]`;
115 return index;
116 }
117 }
118
119 if (typeof thing === 'function') {
120 throw new DevalueError(`Cannot stringify a function`, keys, thing, value);
121 } else if (typeof thing === 'symbol') {
122 throw new DevalueError(`Cannot stringify a Symbol primitive`, keys, thing, value);
123 }
124
125 /** @type {string | Promise<any>} */
126 let str = '';
127
128 if (is_primitive(thing)) {
129 str = stringify_primitive(thing);
130 } else if (typeof thing.then === 'function') {
131 if (!async) {
132 throw new DevalueError(
133 `Cannot stringify a Promise or thenable — use stringifyAsync instead`,
134 keys,
135 thing,
136 value
137 );
138 }
139
140 str = Promise.resolve(thing).then((value) => {
141 const i = flatten(value, index);
142 if (i < 0) stringified[index] = i;
143 });
144 } else {
145 const type = get_type(thing);
146
147 switch (type) {
148 case 'Number':
149 case 'String':
150 case 'Boolean':
151 case 'BigInt':
152 str = `["Object",${flatten(thing.valueOf())}]`;
153 break;
154
155 case 'Date':
156 const valid = !isNaN(thing.getDate());

Callers 1

runFunction · 0.85

Calls 9

is_primitiveFunction · 0.90
get_typeFunction · 0.90
stringify_stringFunction · 0.90
valid_array_indicesFunction · 0.90
is_plain_objectFunction · 0.90
enumerable_symbolsFunction · 0.90
stringify_keyFunction · 0.90
fnFunction · 0.85
stringify_primitiveFunction · 0.70

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…