keyMap.js 916 B

123456789101112131415161718192021222324252627282930313233343536
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.default = 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. *
  13. * const phoneBook = [
  14. * { name: 'Jon', num: '555-1234' },
  15. * { name: 'Jenny', num: '867-5309' }
  16. * ]
  17. *
  18. * // { Jon: { name: 'Jon', num: '555-1234' },
  19. * // Jenny: { name: 'Jenny', num: '867-5309' } }
  20. * const entriesByName = keyMap(
  21. * phoneBook,
  22. * entry => entry.name
  23. * )
  24. *
  25. * // { name: 'Jenny', num: '857-6309' }
  26. * const jennyEntry = entriesByName['Jenny']
  27. *
  28. */
  29. function keyMap(list, keyFn) {
  30. return list.reduce(function (map, item) {
  31. map[keyFn(item)] = item;
  32. return map;
  33. }, Object.create(null));
  34. }