| 54 | } |
| 55 | |
| 56 | function serializeInner( |
| 57 | out: string[], |
| 58 | indexes: Map<unknown, number>, |
| 59 | value: unknown, |
| 60 | custom: Stringifiers | undefined, |
| 61 | ): number { |
| 62 | const seenIdx = indexes.get(value); |
| 63 | if (seenIdx !== undefined) return seenIdx; |
| 64 | |
| 65 | if (value === undefined) return UNDEFINED; |
| 66 | if (value === null) return NULL; |
| 67 | if (Number.isNaN(value)) return NAN; |
| 68 | if (value === Infinity) return INFINITY_POS; |
| 69 | if (value === -Infinity) return INFINITY_NEG; |
| 70 | if (value === 0 && 1 / value < 0) return ZERO_NEG; |
| 71 | |
| 72 | const idx = out.length; |
| 73 | out.push(""); |
| 74 | indexes.set(value, idx); |
| 75 | |
| 76 | let str = ""; |
| 77 | |
| 78 | if (typeof value === "number") { |
| 79 | str += String(value); |
| 80 | } else if (typeof value === "boolean") { |
| 81 | str += String(value); |
| 82 | } else if (typeof value === "bigint") { |
| 83 | str += `["BigInt","${value}"]`; |
| 84 | } else if (typeof value === "string") { |
| 85 | str += JSON.stringify(value); |
| 86 | } else if (Array.isArray(value)) { |
| 87 | str += "["; |
| 88 | for (let i = 0; i < value.length; i++) { |
| 89 | if (i in value) { |
| 90 | str += serializeInner(out, indexes, value[i], custom); |
| 91 | } else { |
| 92 | str += HOLE; |
| 93 | } |
| 94 | |
| 95 | if (i < value.length - 1) { |
| 96 | str += ","; |
| 97 | } |
| 98 | } |
| 99 | str += "]"; |
| 100 | } else if (typeof value === "object") { |
| 101 | if (custom !== undefined) { |
| 102 | for (const k in custom) { |
| 103 | const fn = custom[k]; |
| 104 | if (fn === undefined) continue; |
| 105 | |
| 106 | const res = fn(value); |
| 107 | if (res === undefined) continue; |
| 108 | |
| 109 | const innerIdx = serializeInner(out, indexes, res.value, custom); |
| 110 | str = `["${k}",${innerIdx}]`; |
| 111 | out[idx] = str; |
| 112 | return idx; |
| 113 | } |