-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
46 lines (35 loc) · 969 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
'use strict';
var pathToObject = function(path, value) {
var depths = path.split('.');
var obj = {};
toSubObject(obj);
function toSubObject(sub) {
var shifted = depths.shift();
sub[shifted] = {};
if (depths.length) {
toSubObject(sub[shifted]);
} else {
sub[shifted] = value || {};
}
}
return obj;
};
pathToObject.value = function(obj, path, value) {
var depths = path.split('.');
var val;
setDeep(obj);
function setDeep(subObject) {
var shifted = depths.shift();
if (depths.length) {
setDeep(subObject[shifted]);
} else {
if (value !== undefined) {
subObject[shifted] = value;
} else {
val = subObject[shifted];
}
}
}
return val !== undefined ? val : obj;
};
module.exports = pathToObject;