Last active
April 8, 2021 07:42
-
-
Save matsuby/c317309bb466fc712b7310dc9ea24486 to your computer and use it in GitHub Desktop.
時系列データの累積和
This file contains 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
/** | |
* cumulativeSumObjects({ | |
* 20200101: {a: 1, b: 2, c: 3}, | |
* 20200102: {b: 1, c: 2, d: 3}, | |
* 20200103: {c: 1, d: 2, e: 3}, | |
* }) | |
* => { | |
* 20200101: {a: 1, b: 2, c: 3, d: 0, e: 0}, | |
* 20200102: {a: 1, b: 3, c: 5, d: 3, e: 0}, | |
* 20200103: {a: 1, b: 3, c: 6, d: 5, e: 3}, | |
* } | |
*/ | |
type SeriesItem = Record<string, number> | |
type SeriesObjects = Record<string, SeriesItem> | |
const cumulativeSumObjects = (seriesData: SeriesObjects) => { | |
const baseRecord = Object.values(seriesData).reduce((acc, cur) => { | |
Object.keys(cur).forEach((k) => (acc[k] = 0)) | |
return acc | |
}, {}) | |
const sumObjects = (objects: SeriesItem[]) => | |
objects.reduce( | |
(acc, cur) => { | |
Object.entries(cur).forEach(([k, v]) => { | |
acc[k] = (acc[k] ?? 0) + v | |
}) | |
return acc | |
}, | |
{ ...baseRecord } | |
) | |
return Object.entries(seriesData).reduce((acc: SeriesObjects, [k], i) => { | |
const targets = Object.values(seriesData).filter((_, _i) => _i <= i) | |
acc[k] = sumObjects(targets) | |
return acc | |
}, {}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment