diff options
Diffstat (limited to 'src/util/sugar.js')
-rw-r--r-- | src/util/sugar.js | 58 |
1 files changed, 56 insertions, 2 deletions
diff --git a/src/util/sugar.js b/src/util/sugar.js index e060f458..3fa3fb46 100644 --- a/src/util/sugar.js +++ b/src/util/sugar.js @@ -136,6 +136,23 @@ export function stitchArrays(keyToArray) { return results; } +// Like Map.groupBy! Collects the items of an unsorted array into buckets +// according to a per-item computed value. +export function groupArray(items, fn) { + const buckets = new Map(); + + for (const [index, item] of Array.prototype.entries.call(items)) { + const key = fn(item, index); + if (buckets.has(key)) { + buckets.get(key).push(item); + } else { + buckets.set(key, [item]); + } + } + + return buckets; +} + // Turns this: // // [ @@ -183,8 +200,14 @@ export const compareArrays = (arr1, arr2, {checkOrder = true} = {}) => : arr1.every((x) => arr2.includes(x))); // Stolen from jq! Which pro8a8ly stole the concept from other places. Nice. -export const withEntries = (obj, fn) => - Object.fromEntries(fn(Object.entries(obj))); +export const withEntries = (obj, fn) => { + const result = fn(Object.entries(obj)); + if (result instanceof Promise) { + return result.then(entries => Object.fromEntries(entries)); + } else { + return Object.fromEntries(result); + } +} export function setIntersection(set1, set2) { const intersection = new Set(); @@ -260,6 +283,16 @@ export function delay(ms) { return new Promise((res) => setTimeout(res, ms)); } +export function promiseWithResolvers() { + let obj = {}; + + obj.promise = + new Promise((...opts) => + ([obj.resolve, obj.reject] = opts)); + + return obj; +} + // Stolen from here: https://stackoverflow.com/a/3561711 // // There's a proposal for a native JS function like this, 8ut it's not even @@ -315,6 +348,27 @@ export function cutStart(text, length = 40) { } } +// Wrapper function around wrap(), ha, ha - this requires the Node module +// 'node-wrap'. +export function indentWrap(str, { + wrap, + spaces = 0, + width = 60, + bullet = false, +}) { + const wrapped = + wrap(str, { + width: width - spaces, + indent: ' '.repeat(spaces), + }); + + if (bullet) { + return wrapped.trimStart(); + } else { + return wrapped; + } +} + // Annotates {index, length} results from another iterator with contextual // details, including: // |