keyValMap.js 720 B

123456789101112131415161718192021222324252627282930313233
  1. 'use strict';
  2. Object.defineProperty(exports, '__esModule', {
  3. value: true,
  4. });
  5. exports.keyValMap = 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. * ```ts
  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. const result = Object.create(null);
  25. for (const item of list) {
  26. result[keyFn(item)] = valFn(item);
  27. }
  28. return result;
  29. }