| 77 | } |
| 78 | |
| 79 | export const flatMorph: FlatMorph = ( |
| 80 | o: object, |
| 81 | flatMapEntry: (...args: any[]) => listable<GroupableEntry> |
| 82 | ): any => { |
| 83 | const result: any = {} |
| 84 | const inputIsArray = Array.isArray(o) |
| 85 | let outputShouldBeArray = false |
| 86 | |
| 87 | const entries = Object.entries(o) |
| 88 | for (let i = 0; i < entries.length; i++) { |
| 89 | const entry = entries[i] |
| 90 | const mapped = |
| 91 | inputIsArray ? |
| 92 | flatMapEntry(i, entry[1]) |
| 93 | : flatMapEntry(entry[0], entry[1], i) |
| 94 | |
| 95 | outputShouldBeArray ||= typeof mapped[0] === "number" |
| 96 | |
| 97 | const flattenedEntries = |
| 98 | Array.isArray(mapped[0]) || mapped.length === 0 ? |
| 99 | // if we have an empty array (for filtering) or an array with |
| 100 | // another array as its first element, treat it as a list |
| 101 | (mapped as GroupableEntry[]) |
| 102 | // otherwise, it should be a single entry, so nest it in a tuple |
| 103 | // so it doesn't get spread when the result is flattened |
| 104 | : [mapped as GroupableEntry] |
| 105 | |
| 106 | for (let j = 0; j < flattenedEntries.length; j++) { |
| 107 | const k = flattenedEntries[j][0] |
| 108 | const v = flattenedEntries[j][1] |
| 109 | if (typeof k === "object") { |
| 110 | const existing = hasOwn(result, k.group) ? result[k.group] : undefined |
| 111 | defineValue(result, k.group, append(existing, v)) |
| 112 | } else if (k === "__proto__") defineValue(result, k, v) |
| 113 | else result[k] = v |
| 114 | } |
| 115 | } |
| 116 | |
| 117 | return outputShouldBeArray ? Object.values(result) : result |
| 118 | } |