|
1 |
| -// Map values in an object |
2 |
| -const mapValues = (obj, fn) => Object.fromEntries(Object.entries(obj).map(([k, v]) => [k, fn(v)])); |
| 1 | +module.exports = { |
| 2 | + // ================================================= Array helpers ================================================= |
3 | 3 |
|
4 |
| -// Cartesian product of a list of arrays |
5 |
| -const product = (...arrays) => arrays.reduce((a, b) => a.flatMap(ai => b.map(bi => [...ai, bi])), [[]]); |
6 |
| -const unique = (...array) => array.filter((obj, i) => array.indexOf(obj) === i); |
7 |
| -const zip = (...args) => |
8 |
| - Array.from({ length: Math.max(...args.map(array => array.length)) }, (_, i) => args.map(array => array[i])); |
| 4 | + // Cut an array into an array of sized-length arrays |
| 5 | + // Example: chunk([1,2,3,4,5,6,7,8], 3) → [[1,2,3],[4,5,6],[7,8]] |
| 6 | + chunk: (array, size = 1) => |
| 7 | + Array.from({ length: Math.ceil(array.length / size) }, (_, i) => array.slice(i * size, i * size + size)), |
9 | 8 |
|
10 |
| -module.exports = { |
11 |
| - mapValues, |
12 |
| - product, |
13 |
| - unique, |
14 |
| - zip, |
| 9 | + // Cartesian cross product of an array of arrays |
| 10 | + // Example: product([1,2],[a,b,c],[true]) → [[1,a,true],[1,b,true],[1,c,true],[2,a,true],[2,b,true],[2,c,true]] |
| 11 | + product: (...arrays) => arrays.reduce((a, b) => a.flatMap(ai => b.map(bi => [...ai, bi])), [[]]), |
| 12 | + |
| 13 | + // Range from start to end in increment |
| 14 | + // Example: range(17,42,7) → [17,24,31,38] |
| 15 | + range: (start, stop = undefined, step = 1) => { |
| 16 | + if (!stop) { |
| 17 | + stop = start; |
| 18 | + start = 0; |
| 19 | + } |
| 20 | + return start < stop ? Array.from({ length: Math.ceil((stop - start) / step) }, (_, i) => start + i * step) : []; |
| 21 | + }, |
| 22 | + |
| 23 | + // Unique elements, with an optional getter function |
| 24 | + // Example: unique([1,1,2,3,4,8,1,3,8,13,42]) → [1,2,3,4,8,13,42] |
| 25 | + unique: (array, op = x => x) => array.filter((obj, i) => array.findIndex(entry => op(obj) === op(entry)) === i), |
| 26 | + |
| 27 | + // Zip arrays together. If some arrays are smaller, undefined is used as a filler. |
| 28 | + // Example: zip([1,2],[a,b,c],[true]) → [[1,a,true],[2,b,undefined],[undefined,c,undefined]] |
| 29 | + zip: (...args) => Array.from({ length: Math.max(...args.map(arg => arg.length)) }, (_, i) => args.map(arg => arg[i])), |
| 30 | + |
| 31 | + // ================================================ Object helpers ================================================= |
| 32 | + |
| 33 | + // Create a new object by mapping the values through a function, keeping the keys |
| 34 | + // Example: mapValues({a:1,b:2,c:3}, x => x**2) → {a:1,b:4,c:9} |
| 35 | + mapValues: (obj, fn) => Object.fromEntries(Object.entries(obj).map(([k, v]) => [k, fn(v)])), |
15 | 36 | };
|
0 commit comments