-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathGM_UNPIVOT.ts
70 lines (63 loc) · 2.18 KB
/
GM_UNPIVOT.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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import flatten from "lodash/flatten";
import {
GmTable,
GmTableRowWithTimesAcrossColumns
} from "./gsheetsData/gmTableStructure";
import { preProcessInputRangeWithHeaders } from "./lib/cleanInputRange";
/**
* Unpivots a standard pivoted Gapminder table [geo, name, ...time-values-across-columns], converting the data column headers into time units and the column values as concept values.
*
* @param input_table_range_with_headers The table range to unpivot
* @param time_label (Optional with default "time") the header label to use for the time column
* @param value_label (Optional with default "value") the header label to use for the value column
* @param page_size Optional. Used to paginate large output tables
* @param page Optional. Used to paginate large output tables
* @return A two-dimensional array containing the cell/column contents described above in the summary.
*/
export function GM_UNPIVOT(
input_table_range_with_headers: string[][],
time_label: string,
value_label: string,
page_size: number,
page: number
) {
if (!page_size) {
page_size = null;
}
if (!page) {
page = null;
}
// Ensure expected input range contents
const inputTable = preProcessInputRangeWithHeaders(
input_table_range_with_headers
);
const inputTableRows: GmTableRowWithTimesAcrossColumns[] = inputTable.map(
GmTable.structureRowWithTimesAcrossColumns
);
// Unpivot
const headerTableRow = inputTableRows.shift();
const unpivotedRowsArrays = inputTableRows.map(inputTableRow => {
return GmTable.unpivotRowWithTimesAcrossColumns(
inputTableRow,
headerTableRow
);
});
const unpivotedRows = flatten(unpivotedRowsArrays);
// Use default header labels if not given any
if (time_label === undefined) {
time_label = "time";
}
if (value_label === undefined) {
value_label = "value";
}
// Return as string[][]
const outputTable = [
[headerTableRow.geo, headerTableRow.name, time_label, value_label]
].concat(unpivotedRows.map(GmTable.unstructureRow));
if (page_size) {
const start = page ? (page - 1) * page_size : 0;
const end = start + page_size;
return outputTable.slice(start, end);
}
return outputTable;
}