|
1
|
|
|
/** |
|
2
|
|
|
* Turns an Array into an associative Object (while keeping reference!) |
|
3
|
|
|
* |
|
4
|
|
|
* @param {Array} arr Array of Objects to turn into an |
|
5
|
|
|
* associative Object |
|
6
|
|
|
* @param {String|Array|Function} mapBy optional mapping key, can be a |
|
7
|
|
|
* simple string (property name in |
|
8
|
|
|
* the abjects of arr), a list of |
|
9
|
|
|
* property names (which are |
|
10
|
|
|
* combined) or a function which |
|
11
|
|
|
* returns a unique id to use |
|
12
|
|
|
* |
|
13
|
|
|
* @throws {TypeError} if arr is not an Array or mapBy is set but not of |
|
14
|
|
|
* correct type (String, Array, Function) |
|
15
|
|
|
* |
|
16
|
|
|
* @returns {Object} |
|
17
|
|
|
*/ |
|
18
|
1 |
View Code Duplication |
module.exports = function(arr, mapBy) { |
|
|
|
|
|
|
19
|
7 |
|
var obj = {}; |
|
20
|
|
|
|
|
21
|
7 |
|
if (!Array.isArray(arr)) { |
|
22
|
2 |
|
throw new TypeError('arr argument is not of type Array'); |
|
23
|
|
|
} |
|
24
|
|
|
|
|
25
|
6 |
|
if (mapBy !== undefined |
|
26
|
|
|
&& typeof mapBy !== 'string' |
|
27
|
|
|
&& !Array.isArray(mapBy) |
|
28
|
|
|
&& typeof mapBy !== 'function' |
|
29
|
|
|
) { |
|
30
|
1 |
|
throw new TypeError( |
|
31
|
|
|
'mapBy argument is not of type {String|Array|Function}' |
|
32
|
|
|
); |
|
33
|
|
|
} |
|
34
|
|
|
|
|
35
|
4 |
|
var methods = { |
|
36
|
|
|
string: function(val) { |
|
37
|
3 |
|
this.undefined(val, val[mapBy]); |
|
38
|
|
|
}, |
|
39
|
|
|
object: function(val) { |
|
40
|
3 |
|
var newKey = mapBy.map(function(propertyName){ |
|
41
|
6 |
|
return val[propertyName]; |
|
42
|
|
|
}).join('_'); |
|
43
|
|
|
|
|
44
|
3 |
|
this.undefined(val, newKey); |
|
45
|
|
|
}, |
|
46
|
|
|
function: function(val, i, arr) { |
|
47
|
3 |
|
this.undefined(val, mapBy(val, i, arr)); |
|
48
|
|
|
}, |
|
49
|
|
|
undefined: function(val, newKey) { |
|
50
|
13 |
|
if (typeof newKey === 'string' |
|
51
|
|
|
|| typeof newKey === 'number' |
|
52
|
|
|
) { |
|
53
|
13 |
|
obj[newKey] = val; |
|
54
|
|
|
} |
|
55
|
|
|
} |
|
56
|
|
|
}; |
|
57
|
|
|
|
|
58
|
|
|
/** |
|
59
|
|
|
* run the designated method by mapBy type from the methods object |
|
60
|
|
|
* it binds the methods object so we can use the undefined setter method |
|
61
|
|
|
* for different mapBy types and don't have to maintain multiple but |
|
62
|
|
|
* same conditions |
|
63
|
|
|
*/ |
|
64
|
4 |
|
arr.forEach( |
|
65
|
|
|
methods[(typeof mapBy)].bind(methods) |
|
66
|
|
|
); |
|
67
|
|
|
|
|
68
|
4 |
|
return obj; |
|
69
|
|
|
}; |
|
70
|
|
|
|