keyValMap.mjs 614 B

1234567891011121314151617181920212223242526
  1. /**
  2. * Creates a keyed JS object from an array, given a function to produce the keys
  3. * and a function to produce the values from each item in the array.
  4. * ```ts
  5. * const phoneBook = [
  6. * { name: 'Jon', num: '555-1234' },
  7. * { name: 'Jenny', num: '867-5309' }
  8. * ]
  9. *
  10. * // { Jon: '555-1234', Jenny: '867-5309' }
  11. * const phonesByName = keyValMap(
  12. * phoneBook,
  13. * entry => entry.name,
  14. * entry => entry.num
  15. * )
  16. * ```
  17. */
  18. export function keyValMap(list, keyFn, valFn) {
  19. const result = Object.create(null);
  20. for (const item of list) {
  21. result[keyFn(item)] = valFn(item);
  22. }
  23. return result;
  24. }