keyValMap.js 741 B

123456789101112131415161718192021222324252627282930
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.default = keyValMap;
  6. /**
  7. * Creates a keyed JS object from an array, given a function to produce the keys
  8. * and a function to produce the values from each item in the array.
  9. *
  10. * const phoneBook = [
  11. * { name: 'Jon', num: '555-1234' },
  12. * { name: 'Jenny', num: '867-5309' }
  13. * ]
  14. *
  15. * // { Jon: '555-1234', Jenny: '867-5309' }
  16. * const phonesByName = keyValMap(
  17. * phoneBook,
  18. * entry => entry.name,
  19. * entry => entry.num
  20. * )
  21. *
  22. */
  23. function keyValMap(list, keyFn, valFn) {
  24. return list.reduce(function (map, item) {
  25. map[keyFn(item)] = valFn(item);
  26. return map;
  27. }, Object.create(null));
  28. }