-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
40 lines (31 loc) · 1.15 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import {notNull} from "@softwareventures/nullable";
export type Table = string[][];
export type ReadonlyTable = ReadonlyArray<ReadonlyArray<string>>;
export function* tableToRecords(table: ReadonlyTable): Iterable<Record<string, string>> {
const header = notNull(table[0]);
for (let i = 1; i < table.length; ++i) {
const row = notNull(table[i]);
const record: Record<string, string> = {};
for (let j = 0; j < row.length && j < header.length; ++j) {
const name = notNull(header[j]);
record[name] = notNull(row[j]);
}
yield record;
}
}
export function recordsToTable(records: ReadonlyArray<Readonly<Record<string, string>>>): Table {
if (records.length === 0) {
return [];
}
const headers = Object.keys(notNull(records[0]));
return [headers]
.concat(records
.map(record => headers
.map(header => {
if (header in record) {
return notNull(record[header]);
} else {
throw new Error("Inconsistent records.");
}
})));
}