keyValMap.js.flow 780 B

12345678910111213141516171819202122232425262728293031
  1. // @flow strict
  2. import { type ObjMap } from './ObjMap';
  3. /**
  4. * Creates a keyed JS object from an array, given a function to produce the keys
  5. * and a function to produce the values from each item in the array.
  6. *
  7. * const phoneBook = [
  8. * { name: 'Jon', num: '555-1234' },
  9. * { name: 'Jenny', num: '867-5309' }
  10. * ]
  11. *
  12. * // { Jon: '555-1234', Jenny: '867-5309' }
  13. * const phonesByName = keyValMap(
  14. * phoneBook,
  15. * entry => entry.name,
  16. * entry => entry.num
  17. * )
  18. *
  19. */
  20. export default function keyValMap<T, V>(
  21. list: $ReadOnlyArray<T>,
  22. keyFn: (item: T) => string,
  23. valFn: (item: T) => V,
  24. ): ObjMap<V> {
  25. return list.reduce((map, item) => {
  26. map[keyFn(item)] = valFn(item);
  27. return map;
  28. }, Object.create(null));
  29. }