keyMap.js.flow 936 B

1234567891011121314151617181920212223242526272829303132333435
  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. * for each value in the array.
  6. *
  7. * This provides a convenient lookup for the array items if the key function
  8. * produces unique results.
  9. *
  10. * const phoneBook = [
  11. * { name: 'Jon', num: '555-1234' },
  12. * { name: 'Jenny', num: '867-5309' }
  13. * ]
  14. *
  15. * // { Jon: { name: 'Jon', num: '555-1234' },
  16. * // Jenny: { name: 'Jenny', num: '867-5309' } }
  17. * const entriesByName = keyMap(
  18. * phoneBook,
  19. * entry => entry.name
  20. * )
  21. *
  22. * // { name: 'Jenny', num: '857-6309' }
  23. * const jennyEntry = entriesByName['Jenny']
  24. *
  25. */
  26. export default function keyMap<T>(
  27. list: $ReadOnlyArray<T>,
  28. keyFn: (item: T) => string,
  29. ): ObjMap<T> {
  30. return list.reduce((map, item) => {
  31. map[keyFn(item)] = item;
  32. return map;
  33. }, Object.create(null));
  34. }