-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.js
47 lines (43 loc) · 959 Bytes
/
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
var parsePath = require('./ParsePath');
var hasOwnProp = Object.prototype.hasOwnProperty;
function get(obj, path) {
if (path === undefined || path === null) {
return obj;
}
var result = null;
var keys = typeof path == 'string' ?
parsePath(path) :
Array.isArray(path) ? path : [path];
result = obj
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
if (!result || !hasOwnProp.call(result, key)) {
result = undefined;
break;
}
result = result[key];
}
return result;
}
function set(obj, path, value) {
if (path === undefined || path === null) {
return false;
}
var keys = typeof path == 'string' ?
parsePath(path) :
Array.isArray(path) ? path : [path];
for (var i = 0; i < keys.length - 1; i++) {
var key = keys[i];
if (!hasOwnProp.call(obj, key)) {
return false;
};
obj = obj[key];
}
obj[keys[i]] = value;
return true;
}
module.exports = {
parse: parsePath,
set: set,
get: get
}