keyMap.js 904 B

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