iterate.js 1.9 KB

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