« get me outta code hell

hsmusic-wiki - HSMusic - static wiki software cataloguing collaborative creation
about summary refs log tree commit diff
path: root/src/util/sugar.js
diff options
context:
space:
mode:
Diffstat (limited to 'src/util/sugar.js')
-rw-r--r--src/util/sugar.js14
1 files changed, 14 insertions, 0 deletions
diff --git a/src/util/sugar.js b/src/util/sugar.js
index 2883d94..754f199 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));