forked from juliangruber/deep-access
-
Notifications
You must be signed in to change notification settings - Fork 12
/
index.cjs
40 lines (36 loc) · 996 Bytes
/
index.cjs
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
function deep () {
if (arguments.length === 2) return get.apply(null, arguments);
return set.apply(null, arguments);
}
function get (obj, path) {
var keys = Array.isArray(path) ? path : path.split('.');
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
if (!obj || !Object.hasOwn(obj, key) || isUnsafeKey(key)) {
obj = undefined;
break;
}
obj = obj[key];
}
return obj;
}
function set (obj, path, value, strict = !deep.p) {
var keys = Array.isArray(path) ? path : path.split('.');
for (var i = 0; i < keys.length - 1; i++) {
var key = keys[i];
if (isUnsafeKey(key)) return;
if (!Object.hasOwn(obj, key) && !strict) obj[key] = {};
obj = obj[key];
}
obj[keys[i]] = value;
return value;
}
function isUnsafeKey (key) {
return (Array.isArray(key) && key[0] === '__proto__')
|| key === '__proto__'
|| key === 'constructor'
|| key === 'prototype';
}
module.exports = deep;
exports.set = set;
exports.get = get;