|
| 1 | +/** Async version of Array.prototype.reduce() |
| 2 | + * await reduce(['/foo', '/bar', '/baz'], async (acc, v) => { |
| 3 | + * acc[v] = await (await fetch(v)).json(); |
| 4 | + * return acc; |
| 5 | + * }, {}); |
| 6 | + */ |
| 7 | +export async function reduce(arr, fn, val, pure) { |
| 8 | + for (let i=0; i<arr.length; i++) { |
| 9 | + let v = await fn(val, arr[i], i, arr); |
| 10 | + if (pure!==false) val = v; |
| 11 | + } |
| 12 | + return val; |
| 13 | +} |
| 14 | + |
| 15 | +/** Async version of Array.prototype.map() |
| 16 | + * await map(['foo', 'baz'], async v => await fetch(v) ) |
| 17 | + */ |
| 18 | +export async function map(arr, fn) { |
| 19 | + return await reduce(arr, async (acc, value, index, arr) => { |
| 20 | + acc.push(await fn(value, index, arr)); |
| 21 | + }, [], false); |
| 22 | +} |
| 23 | + |
| 24 | +/** Async version of Array.prototype.filter() |
| 25 | + * await filter(['foo', 'baz'], async v => (await fetch(v)).ok ) |
| 26 | + */ |
| 27 | +export async function filter(arr, fn) { |
| 28 | + return await reduce(arr, async (acc, value, index, arr) => { |
| 29 | + if (await fn(value, index, arr)) acc.push(value); |
| 30 | + }, [], false); |
| 31 | +} |
| 32 | + |
| 33 | +function identity(x) { |
| 34 | + return x; |
| 35 | +} |
| 36 | + |
| 37 | +function resolve(list) { |
| 38 | + let out = Array.isArray(list) ? [] : {}; |
| 39 | + for (let i in list) if (list.hasOwnProperty(i)) out[i] = list[i](); |
| 40 | + return out; |
| 41 | +} |
| 42 | + |
| 43 | +/** Provided by standard lib, replaces async.parallel() |
| 44 | + * await parallel([ |
| 45 | + * () => fetch('foo'), |
| 46 | + * () => fetch('baz') |
| 47 | + * ]) |
| 48 | + */ |
| 49 | +export async function parallel(list) { |
| 50 | + return await Promise.all(resolve(list)); |
| 51 | +} |
| 52 | + |
| 53 | +/** Replaces async.series() |
| 54 | + * await series([ |
| 55 | + * () => fetch('foo'), |
| 56 | + * () => fetch('baz') |
| 57 | + * ]) |
| 58 | + */ |
| 59 | +export async function series(list) { |
| 60 | + return await map(resolve(list), identity); |
| 61 | +} |
0 commit comments