Repository navigation
Expand file tree
/
Copy pathindex.js
More file actions
69 lines (58 loc) · 1.83 KB
/
Copy pathindex.js
File metadata and controls
69 lines (58 loc) · 1.83 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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
exports.parse = function(name) {
return name.split(/[\.\[]+/g).map(function(part) {
// strip the "]" from the string, it's not needed after the split
part = part.replace(/\]$/, "");
// if the string is now empty, we're dealing with an array
if (!part) return false;
// if the key is just numbers, parse it
if (/^\d+$/.test(part)) return parseInt(part, 10);
// otherwise, return string key name
return part;
});
};
exports.set = function(o, key, value) {
if (!o) o = {}; // create an empty object if needed
return exports.parse(key).reduce(function(acc, branch, x, branches) {
// while we are setting the various branches on our object
if (x + 1 < branches.length) {
// we need to see what key is coming next
var nextKey = branches[x + 1];
// when working with an array
if (branch === false) {
// first inspect the last item on the array
var temp = acc[acc.length - 1];
if (!temp || branchesExist(temp, branches.slice(x + 1))) {
temp = {};
acc.push(temp);
}
return temp;
} else {
// when the branch does not already exist
if (!(branch in acc)) {
// depending on nextKey, we may be setting an array or an object
acc[branch] = (nextKey === false || typeof nextKey === "number") ? [] : {};
}
return acc[branch];
}
// the last iteration just sets a simple property / appends to an array
} else {
if (branch === false) {
acc.push(value);
} else {
acc[branch] = value;
}
return o;
}
}, o);
};
function branchesExist(o, branches) {
var current = o;
return branches.every(function(branch) {
if (branch in current) {
current = current[branch];
return true;
} else {
return false;
}
});
}