-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
102 lines (92 loc) · 2.6 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
/**
* @module transformProps.
*
* Some of these mini-functions were broken out to increase performance.
*/
/**
* @param {mixed} memo is the current value of the prop.
* @param {function} transformer is a function.
* @return {mixed}
*/
function reducer(memo, transformer) {
return transformer(memo);
}
/**
* @param {object} object
* @param {function[]} transformers
* @param {string[]} propKeys
* @param {string} k
*/
function forEachKey(object, transformers, propKeys, k) {
var v = object[k];
if (propKeys.hasOwnProperty(k)) {
object[k] = transformers.reduce(reducer, v);
return;
}
if (!(typeof v === 'object' && v !== null)) return;
iterate(v, transformers, propKeys);
}
/**
* @param {object} object
* @param {function[]} transformers
* @param {string[]} propKeys
*/
function iterate(object, transformers, propKeys) {
Object.keys(object).forEach(forEachKey.bind(null, object, transformers, propKeys));
}
/**
* @param {function | function[]} transformers
*/
function throwIfNotFuncOrAryOfFunc(transformers) {
if (
Array.isArray(transformers) && transformers.find(function find(item) {
return typeof item !== 'function';
})
||
!Array.isArray(transformers) && typeof transformers !== 'function'
) {
throw new TypeError('Expected @transformers to be a function or array of functions but received: "' + transformers + '".');
}
}
/**
* @param {object} object
*/
function throwIfNotObj(object) {
if (!(typeof object === 'object' && object !== null)) {
throw new TypeError('Expected @object to be an object but received: "' + object + '".');
}
}
/**
* @param {str | str[]} propKeys
*/
function throwIfNotStrOrAryOfStr(propKeys) {
if (
Array.isArray(propKeys) && propKeys.find(function find(item) {
return typeof item !== 'string';
})
||
!Array.isArray(propKeys) && typeof propKeys !== 'string'
) {
throw new TypeError('Expected @propKeys to be a string or array of strings but received: "' + propKeys + '".');
}
}
/**
* @param {object} object
* @param {function[]} transformers
* @param {string[]} propKeys
* @return {object}
*/
function transformProps(object, transformers, propKeys) {
throwIfNotObj(object);
throwIfNotFuncOrAryOfFunc(transformers);
throwIfNotStrOrAryOfStr(propKeys);
transformers = Array.isArray(transformers) ? transformers : [transformers];
propKeys = Array.isArray(propKeys) ? propKeys : [propKeys];
propKeys = propKeys.reduce(function reduce(memo, propKey) {
memo[propKey] = 1;
return memo;
}, {});
iterate(object, transformers, propKeys);
return object;
}
module.exports = transformProps;