« get me outta code hell

reverse: unique option - hsmusic-wiki - HSMusic - static wiki software cataloguing collaborative creation
about summary refs log tree commit diff
diff options
context:
space:
mode:
author(quasar) nebula <qznebula@protonmail.com>2025-01-11 20:23:54 -0400
committer(quasar) nebula <qznebula@protonmail.com>2025-01-11 20:23:54 -0400
commitbe5966ee63d361f884891ba192c9cac8582b81ab (patch)
treeca95e732d26fc72f637e0de8faf946f3c4b4a96f
parent05446c9ea6f8b20414fa0b22f0a3c091e81e8a48 (diff)
reverse: unique option
-rw-r--r--src/reverse.js32
1 files changed, 29 insertions, 3 deletions
diff --git a/src/reverse.js b/src/reverse.js
index 22746d24..9ad5c8a7 100644
--- a/src/reverse.js
+++ b/src/reverse.js
@@ -3,16 +3,36 @@ import * as fr from './find-reverse.js';
 import {sortByDate} from '#sort';
 import {stitchArrays} from '#sugar';
 
+function checkUnique(value) {
+  if (value.length === 0) {
+    return null;
+  } else if (value.length === 1) {
+    return value[0];
+  } else {
+    throw new Error(
+      `Requested unique referencing thing, ` +
+      `but ${value.length} reference this`);
+  }
+}
+
 function reverseHelper(spec) {
   const cache = new WeakMap();
 
-  return (thing, data) => {
+  return (thing, data, {
+    unique = false,
+  } = {}) => {
     // Check for an existing cache record which corresponds to this data.
     // If it exists, query it for the requested thing, and return that;
     // if it doesn't, create it and put it where it needs to be.
 
     if (cache.has(data)) {
-      return cache.get(data).get(thing) ?? [];
+      const value = cache.get(data).get(thing) ?? [];
+
+      if (unique) {
+        return checkUnique(value);
+      } else {
+        return value;
+      }
     }
 
     const cacheRecord = new WeakMap();
@@ -70,7 +90,13 @@ function reverseHelper(spec) {
     // Then just pluck out the requested thing from the now-filled
     // cache record!
 
-    return cacheRecord.get(thing) ?? [];
+    const value = cacheRecord.get(thing) ?? [];
+
+    if (unique) {
+      return checkUnique(value);
+    } else {
+      return value;
+    }
   };
 }