-
Notifications
You must be signed in to change notification settings - Fork 104
/
getitem.js
98 lines (86 loc) · 2.07 KB
/
getitem.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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
function get(path, hash) {
var parts = path.split('.');
if (!hash || !parts) return undefined;
var i = 0,
current = hash;
// return the parent and the last item
for (; i < parts.length; i++) {
if (typeof current[parts[i]] === 'undefined') {
return undefined;
}
current = current[parts[i]];
}
return current;
}
function set(path, value, hash) {
var parts = path.split('.'),
last = parts[parts.length - 1],
rest = parts.slice(0, parts.length - 1);
var i = 0,
current = hash;
// return the parent and the last item
for (; i < rest.length; i++) {
if (!current[parts[i]]) {
current[parts[i]] = {};
}
current = current[parts[i]];
}
if (current) {
current[last] = value;
}
}
function remove(path, value, hash) {
var parts = path.split('.'),
last = parts[parts.length - 1],
rest = parts.slice(0, parts.length - 1);
var i = 0,
current = hash;
// return the parent and the last item
for (; i < rest.length; i++) {
if (!current[parts[i]]) {
current[parts[i]] = {};
}
current = current[parts[i]];
}
if (current) {
var index;
if (!value || current[last] == value) {
delete current[last];
return;
}
if (Array.isArray(current[last])) {
index = current[last].indexOf(value);
current[last].splice(index, 1);
}
}
}
function add(path, value, hash) {
var parts = path.split('.'),
last = parts[parts.length - 1],
rest = parts.slice(0, parts.length - 1);
// console.log(rest, last);
var i = 0,
current = hash;
// return the parent and the last item
for (; i < rest.length; i++) {
if (!current[parts[i]]) {
current[parts[i]] = {};
}
current = current[parts[i]];
}
if (current) {
if (!current[last]) {
current[last] = [];
}
if (!Array.isArray(current[last])) {
current[last] = [current[last]];
}
if (current[last].indexOf(value) === -1) {
current[last].push(value);
}
}
}
exports.get = get;
exports.set = set;
exports.add = add;
exports.remove = remove;