UNPKG

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