UNPKG

1.12 kBJavaScriptView Raw
1'use strict';
2
3Object.defineProperty(exports, "__esModule", {
4 value: true
5});
6exports.default = keyMap;
7
8
9/**
10 * Creates a keyed JS object from an array, given a function to produce the keys
11 * for each value in the array.
12 *
13 * This provides a convenient lookup for the array items if the key function
14 * produces unique results.
15 *
16 * const phoneBook = [
17 * { name: 'Jon', num: '555-1234' },
18 * { name: 'Jenny', num: '867-5309' }
19 * ]
20 *
21 * // { Jon: { name: 'Jon', num: '555-1234' },
22 * // Jenny: { name: 'Jenny', num: '867-5309' } }
23 * const entriesByName = keyMap(
24 * phoneBook,
25 * entry => entry.name
26 * )
27 *
28 * // { name: 'Jenny', num: '857-6309' }
29 * const jennyEntry = entriesByName['Jenny']
30 *
31 */
32function keyMap(list, keyFn) {
33 return list.reduce(function (map, item) {
34 return map[keyFn(item)] = item, map;
35 }, Object.create(null));
36} /**
37 * Copyright (c) 2015-present, Facebook, Inc.
38 *
39 * This source code is licensed under the MIT license found in the
40 * LICENSE file in the root directory of this source tree.
41 *
42 *
43 */
\No newline at end of file