iterate.js 559 B

1234567891011121314151617
  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(Math.max(...args.map(array => array.length)))
  8. .fill()
  9. .map((_, i) => args.map(array => array[i]));
  10. module.exports = {
  11. mapValues,
  12. product,
  13. unique,
  14. zip,
  15. };