Last active
November 4, 2022 03:04
-
-
Save maxsei/ee7119dfde8eefb23e7e293df24b4f8a to your computer and use it in GitHub Desktop.
verbose code that pivots an array of records in a very unperformant and naive way.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| const rdate = () => new Date(parseInt(Math.random() * Number.MAX_SAFE_INTEGER)); | |
| const data = [ | |
| { Symbol: 'a', Data: 0.0, At: rdate() }, | |
| { Symbol: 'b', Data: 0.0, At: rdate() }, | |
| { Symbol: 'c', Data: 1.0, At: rdate() }, | |
| { Symbol: 'a', Data: 1.0, At: rdate() }, | |
| { Symbol: 'c', Data: 0.0, At: rdate() }, | |
| { Symbol: 'b', Data: 1.0, At: rdate() }, | |
| { Symbol: 'd', Data: 0.0, At: rdate() }, | |
| ]; | |
| const muhPivotTable = [ | |
| ...data | |
| .reduce( | |
| (acc, cur) => | |
| ((acc) => ({ | |
| columns: acc.columns, | |
| // Append a pivoted version of record to at the index | |
| index: acc.index.set(cur['At'], [ | |
| ...(acc.index.get(cur['At']) ?? []), | |
| [...acc.columns.keys()].reduce( | |
| (o: Record<string, any | null>, k: string) => ({ | |
| ...o, | |
| ...{ [k]: cur['Data'] ?? null }, | |
| }), | |
| { At: cur['At'] }, | |
| ), | |
| ]), | |
| }))( | |
| acc.columns.has(cur['Symbol']) | |
| ? acc | |
| : // If we haven't see this column before add it to the unique columns and | |
| // add nulls for the current column key. | |
| { | |
| columns: acc.columns.add(cur['Symbol']), | |
| index: new Map( | |
| [...acc.index.entries()].map(([k, vv]) => [ | |
| k, | |
| vv.map((v: Record<string, any>) => ({ | |
| ...v, | |
| [cur['Symbol']]: null, | |
| })), | |
| ]), | |
| ), | |
| }, | |
| ), | |
| { columns: new Set(), index: new Map() }, | |
| // Do your aggregation of collisions here, I'm just taking the first one. | |
| ) | |
| .index.values(), | |
| ].reduce((acc, cur, i) => (i === 0 ? cur : acc), null); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment