From 1455b384058184796279c629c21a754cd8fb4482 Mon Sep 17 00:00:00 2001 From: "(quasar) nebula" Date: Tue, 19 Jul 2022 12:43:09 -0300 Subject: finish porting listing specs (!!) --- src/util/sugar.js | 14 ++++++++++++++ 1 file changed, 14 insertions(+) (limited to 'src/util/sugar.js') 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)); -- cgit 1.3.0-6-gf8a5