« get me outta code hell

new "empty" sugar.js util - 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:
author(quasar) nebula <qznebula@protonmail.com>2022-11-21 21:48:31 -0400
committer(quasar) nebula <qznebula@protonmail.com>2022-11-21 21:48:31 -0400
commitba2751eae00c4bcf10403edbd549ca70dc316cab (patch)
tree492537e39b268dd1991bc85ffb2e4c666ff03536 /src/util/sugar.js
parent860b9fbf12315362d2c33864521c3f081fd66545 (diff)
new "empty" sugar.js util
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 c836d0ce..24ae8639 100644
--- a/src/util/sugar.js
+++ b/src/util/sugar.js
@@ -30,6 +30,20 @@ export function* splitArray(array, fn) {
   }
 }
 
+// Null-accepting function to check if an array is empty. Accepts null (and
+// treats as empty) as a shorthand for "hey, check if this property is an array
+// with/without stuff in it" for objects where properties that are PRESENT but
+// don't currently have a VALUE are null (instead of undefined).
+export function empty(arrayOrNull) {
+  if (arrayOrNull === null) {
+    return true;
+  } else if (Array.isArray(arrayOrNull)) {
+    return arrayOrNull.length === 0;
+  } else {
+    throw new Error(`Expected array or null`);
+  }
+}
+
 // 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