UNPKG

935 BJavaScriptView Raw
1import { roundD2 } from '@aryth/math';
2import { iterate } from '@vect/vector-mapper';
3import { Roller } from '@vect/vector-roller';
4
5const timeseriesRolling = function ({
6 dateLabel = 'date',
7 fields,
8 depth = 4,
9 mutate = true
10}) {
11 /** @type {Table} */
12 const table = mutate ? this : this.copy();
13 const dateIndex = table.coin(dateLabel),
14 indexes = table.columnIndexes(fields),
15 indexCount = indexes.length;
16 if (indexes.includes(dateIndex)) indexes.splice(indexes.indexOf(dateIndex), 1);
17 const rows = table.rows;
18
19 for (const collection of Roller.build(rows, depth)) iterate(indexes, y => collection[0][y] = roundD2(columnSum(collection, y, depth)), indexCount);
20
21 rows.splice(-depth + 1);
22 return table.boot({
23 rows
24 });
25};
26
27const columnSum = (rows, y, h) => {
28 h = h || rows.height;
29 let sum = 0;
30
31 for (let i = 0; i < h; i++) sum += rows[i][y];
32
33 return sum;
34};
35
36export { timeseriesRolling };