iterate.js 555 B

123456789101112131415
  1. // Map values in an object
  2. const mapValues = (obj, fn) => Object.fromEntries(Object.entries(obj).map(([k, v]) => [k, fn(v)]));
  3. // Cartesian product of a list of arrays
  4. const product = (...arrays) => arrays.reduce((a, b) => a.flatMap(ai => b.map(bi => [...ai, bi])), [[]]);
  5. const unique = (...array) => array.filter((obj, i) => array.indexOf(obj) === i);
  6. const zip = (...args) =>
  7. Array.from({ length: Math.max(...args.map(array => array.length)) }, (_, i) => args.map(array => array[i]));
  8. module.exports = {
  9. mapValues,
  10. product,
  11. unique,
  12. zip,
  13. };