-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
50 lines (46 loc) · 1.21 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
var error = new Error("Invalid path. Please give an array object.");
var getProp = function(object, path_to_key){
if(path_to_key.length === 1)
return object[path_to_key[0]];
else if(path_to_key.length === 0)
throw error;
else{
if(object[path_to_key[0]])
return getProp(object[path_to_key[0]], path_to_key.slice(1));
else{
object[path_to_key[0]] = {};
return getProp(object[path_to_key[0]], path_to_key.slice(1));
}
}
}
var setUpdateProp = function(object, path_to_key, value){
if(path_to_key.length === 1)
object[path_to_key[0]] = value;
else if(path_to_key.length === 0)
throw error;
else{
if(object[path_to_key[0]])
return setUpdateProp(object[path_to_key[0]], path_to_key.slice(1), value);
else{
object[path_to_key[0]] = {};
return setUpdateProp(object[path_to_key[0]], path_to_key.slice(1), value);
}
}
}
var deleteProp = function(object, path_to_key){
if(path_to_key.length === 1)
delete object[path_to_key[0]];
else if(path_to_key.length === 0)
throw error;
else{
if(object[path_to_key[0]])
return deleteProp(object[path_to_key[0]], path_to_key.slice(1));
else
return undefined;
}
};
module.exports = {
get: getProp,
set: setUpdateProp,
remove: deleteProp
};