keyMap.mjs 804 B

123456789101112131415161718192021222324252627282930313233343536
  1. /**
  2. * Creates a keyed JS object from an array, given a function to produce the keys
  3. * for each value in the array.
  4. *
  5. * This provides a convenient lookup for the array items if the key function
  6. * produces unique results.
  7. * ```ts
  8. * const phoneBook = [
  9. * { name: 'Jon', num: '555-1234' },
  10. * { name: 'Jenny', num: '867-5309' }
  11. * ]
  12. *
  13. * const entriesByName = keyMap(
  14. * phoneBook,
  15. * entry => entry.name
  16. * )
  17. *
  18. * // {
  19. * // Jon: { name: 'Jon', num: '555-1234' },
  20. * // Jenny: { name: 'Jenny', num: '867-5309' }
  21. * // }
  22. *
  23. * const jennyEntry = entriesByName['Jenny']
  24. *
  25. * // { name: 'Jenny', num: '857-6309' }
  26. * ```
  27. */
  28. export function keyMap(list, keyFn) {
  29. const result = Object.create(null);
  30. for (const item of list) {
  31. result[keyFn(item)] = item;
  32. }
  33. return result;
  34. }