* @param {boolean} async * @param {any} value * @param {Record any>} [reducers]
(async, value, reducers)
| 73 | * @param {Record<string, (value: any) => any>} [reducers] |
| 74 | */ |
| 75 | function run(async, value, reducers) { |
| 76 | /** @type {any[]} */ |
| 77 | const stringified = []; |
| 78 | |
| 79 | /** @type {Map<any, number>} */ |
| 80 | const indexes = new Map(); |
| 81 | |
| 82 | /** @type {Array<{ key: string, fn: (value: any) => any }>} */ |
| 83 | const custom = []; |
| 84 | if (reducers) { |
| 85 | for (const key of Object.getOwnPropertyNames(reducers)) { |
| 86 | custom.push({ key, fn: reducers[key] }); |
| 87 | } |
| 88 | } |
| 89 | |
| 90 | /** @type {string[]} */ |
| 91 | const keys = []; |
| 92 | |
| 93 | let p = 0; |
| 94 | |
| 95 | /** |
| 96 | * @param {any} thing |
| 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( |
no test coverage detected