From f641a620392c069b516e0b02491f21f007a03dea Mon Sep 17 00:00:00 2001 From: "(quasar) nebula" Date: Sun, 14 Jan 2024 16:31:30 -0400 Subject: sugar: atOffset --- src/util/sugar.js | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) (limited to 'src/util') diff --git a/src/util/sugar.js b/src/util/sugar.js index b0fc1408..2a028f30 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 -- cgit 1.3.0-6-gf8a5