UNPKG

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