« get me outta code hell

sugar: atOffset - hsmusic-wiki - HSMusic - static wiki software cataloguing collaborative creation
about summary refs log tree commit diff
path: root/src/util
diff options
context:
space:
mode:
author(quasar) nebula <qznebula@protonmail.com>2024-01-14 16:31:30 -0400
committer(quasar) nebula <qznebula@protonmail.com>2024-01-14 16:35:02 -0400
commitf641a620392c069b516e0b02491f21f007a03dea (patch)
tree199123ceea222231c9e3cc8dd9070d042c508c6c /src/util
parenta945dbfbe48dadf0a31aa8c633fa8fcf7c8bcbda (diff)
sugar: atOffset
Diffstat (limited to 'src/util')
-rw-r--r--src/util/sugar.js28
1 files changed, 28 insertions, 0 deletions
diff --git a/src/util/sugar.js b/src/util/sugar.js
index b0fc140..2a028f3 100644
--- a/src/util/sugar.js
+++ b/src/util/sugar.js
@@ -60,6 +60,34 @@ export function repeat(times, array) {
   return out;
 }
 
+// Gets the item at an index relative to another index.
+export function atOffset(array, index, offset, {
+  wrap = false,
+  valuePastEdge = null,
+} = {}) {
+  if (index === -1) {
+    return valuePastEdge;
+  }
+
+  if (offset === 0) {
+    return array[index];
+  }
+
+  if (wrap) {
+    return array[(index + offset) % array.length];
+  }
+
+  if (offset > 0 && index + offset > array.length - 1) {
+    return valuePastEdge;
+  }
+
+  if (offset < 0 && index + offset < 0) {
+    return valuePastEdge;
+  }
+
+  return array[index + offset];
+}
+
 // 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