forked from sindresorhus/map-obj
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
52 lines (40 loc) · 1.16 KB
/
index.js
File metadata and controls
52 lines (40 loc) · 1.16 KB
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
'use strict';
// Customized for this use-case
const isObject = x =>
typeof x === 'object' &&
x !== null &&
!(x instanceof RegExp) &&
!(x instanceof Error) &&
!(x instanceof Date);
const isObjectId = value => isObject(value) && value.constructor.name === 'ObjectID';
module.exports = function mapObj(object, fn, options, seen) {
options = Object.assign({
deep: false,
target: {}
}, options);
seen = seen || new WeakMap();
if (seen.has(object)) {
return seen.get(object);
}
seen.set(object, options.target);
const {target} = options;
delete options.target;
const mapArray = array => array.map(x => isObject(x) ? mapObj(x, fn, options, seen) : x);
if (Array.isArray(object)) {
return mapArray(object);
}
/// TODO: Use `Object.entries()` when targeting Node.js 8
for (const key of Object.keys(object)) {
const value = object[key];
let [newKey, newValue] = fn(key, value, object);
if (isObjectId(newValue)) {
target[newKey] = newValue;
} else if (options.deep && isObject(newValue)) {
newValue = Array.isArray(newValue) ?
mapArray(newValue) :
mapObj(newValue, fn, options, seen);
}
target[newKey] = newValue;
}
return target;
};