From 89e79008b02331b69660bb16b6ca737e37483e61 Mon Sep 17 00:00:00 2001 From: "(quasar) nebula" Date: Fri, 23 Jun 2023 19:41:15 -0300 Subject: content: generateCoverCarousel This also introduces a handy stitchArrays() utility, which probably has some uses not caught in this commit. --- src/util/sugar.js | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) (limited to 'src/util/sugar.js') diff --git a/src/util/sugar.js b/src/util/sugar.js index 3a7e6f82..5f54c3b9 100644 --- a/src/util/sugar.js +++ b/src/util/sugar.js @@ -73,6 +73,38 @@ export function accumulateSum(array, fn = x => x) { 0); } +// Stitches together the items of separate arrays into one array of objects +// whose keys are the corresponding items from each array at that index. +// This is mostly useful for iterating over multiple arrays at once! +export function stitchArrays(keyToArray) { + const errors = []; + + for (const [key, value] of Object.entries(keyToArray)) { + if (!Array.isArray(value)) { + errors.push(new TypeError(`(${key}) Expected array, got ${value}`)); + } + } + + if (!empty(errors)) { + throw new AggregateError(errors, `Expected all values to be arrays`); + } + + const keys = Object.keys(keyToArray); + const arrays = Object.values(keyToArray); + const length = Math.max(...arrays.map(({length}) => length)); + const results = []; + + for (let i = 0; i < length; i++) { + const object = {}; + for (const key of keys) { + object[key] = keyToArray[key][i]; + } + results.push(object); + } + + return results; +} + export const mapInPlace = (array, fn) => array.splice(0, array.length, ...array.map(fn)); -- cgit 1.3.0-6-gf8a5