From 36c25f298c5dfb9478157e61aacff53227a0ed1e Mon Sep 17 00:00:00 2001 From: "(quasar) nebula" Date: Wed, 5 Jul 2023 21:53:05 -0300 Subject: content: listArtistsbyLatestContribution: stuck in the array mines --- src/util/sugar.js | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) (limited to 'src/util/sugar.js') diff --git a/src/util/sugar.js b/src/util/sugar.js index 11ff7f01..da21d6d0 100644 --- a/src/util/sugar.js +++ b/src/util/sugar.js @@ -108,6 +108,41 @@ export function stitchArrays(keyToArray) { return results; } +// Turns this: +// +// [ +// [123, 'orange', null], +// [456, 'apple', true], +// [789, 'banana', false], +// [1000, 'pear', undefined], +// ] +// +// Into this: +// +// [ +// [123, 456, 789, 1000], +// ['orange', 'apple', 'banana', 'pear'], +// [null, true, false, undefined], +// ] +// +// And back again, if you call it again on its results. +export function transposeArrays(arrays) { + if (empty(arrays)) { + return []; + } + + const length = arrays[0].length; + const results = new Array(length).fill(null).map(() => []); + + for (const array of arrays) { + for (let i = 0; i < length; i++) { + results[i].push(array[i]); + } + } + + return results; +} + export const mapInPlace = (array, fn) => array.splice(0, array.length, ...array.map(fn)); -- cgit 1.3.0-6-gf8a5