diff options
author | (quasar) nebula <qznebula@protonmail.com> | 2022-07-19 12:43:09 -0300 |
---|---|---|
committer | (quasar) nebula <qznebula@protonmail.com> | 2022-07-19 12:43:09 -0300 |
commit | 1455b384058184796279c629c21a754cd8fb4482 (patch) | |
tree | abf277454e86ba73fac20716a824ce09203feec8 /src/util | |
parent | f474ba28a5a46f39dd51e9d1838c18f07cd14a3d (diff) |
finish porting listing specs (!!)
Diffstat (limited to 'src/util')
-rw-r--r-- | src/util/sugar.js | 14 |
1 files changed, 14 insertions, 0 deletions
diff --git a/src/util/sugar.js b/src/util/sugar.js index 2883d949..754f1991 100644 --- a/src/util/sugar.js +++ b/src/util/sugar.js @@ -30,6 +30,20 @@ export function* splitArray(array, fn) { } } +// Sums the values in an array, optionally taking a function which maps each +// item to a number (handy for accessing a certain property on an array of like +// objects). This also coalesces null values to zero, so if the mapping function +// returns null (or values in the array are nullish), they'll just be skipped in +// the sum. +export function accumulateSum(array, fn = x => x) { + return array.reduce( + (accumulator, value, index, array) => + accumulator + + fn(value, index, array) ?? 0, + 0 + ); +} + export const mapInPlace = (array, fn) => array.splice(0, array.length, ...array.map(fn)); |