-
Notifications
You must be signed in to change notification settings - Fork 6
/
index.js
58 lines (44 loc) · 1.29 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
'use strict';
function deepMap(object, fn, opts) {
opts = opts || {};
if (!fn) {
throwError(Error, 'transformFn must be defined');
} else if (!isFunction(fn)) {
throwError(TypeError, 'transformFn must be a function');
} else if (!isObject(opts)) {
throwError(TypeError, 'options must be an object or undefined');
}
return transform(object, fn, opts);
}
function transform(value, fn, opts, key) {
return Array.isArray(value) ? mapArray(value, fn, opts) :
isObject(value) ? mapObject(value, fn, opts) :
fn.call(opts.thisArg, value, key);
}
function mapArray(array, fn, opts) {
var result = opts.inPlace ? array : [];
var length = array.length;
for (var i = 0; i < length; i++) {
result[i] = transform(array[i], fn, opts, i);
}
return result;
}
function mapObject(object, fn, opts) {
var result = opts.inPlace ? object : {};
for (var key in object) {
result[key] = transform(object[key], fn, opts, key);
}
return result;
}
function isFunction(value) {
return typeof value === 'function';
}
function isObject(value) {
return typeof value === 'object' || isFunction(value);
}
function throwError(ErrorContructor, message) {
var err = new ErrorContructor(message);
Error.captureStackTrace(err, deepMap);
throw err;
}
module.exports = deepMap;