-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathindex.js
99 lines (81 loc) · 1.68 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
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
99
/**
* Set given `path`
*
* @param {Object} obj
* @param {String} path
* @param {Mixed} val
* @return {Object}
* @api public
*/
exports.set = function(obj, path, val) {
var segs = path.split('.');
var attr = segs.pop();
var src = obj;
for (var i = 0; i < segs.length; i++) {
var seg = segs[i];
if (!isSafe(obj, seg)) return src;
obj[seg] = obj[seg] || {};
obj = obj[seg];
}
if (isSafe(obj, attr)) {
obj[attr] = val;
}
return src;
};
/**
* Get given `path`
*
* @param {Object} obj
* @param {String} path
* @return {Mixed}
* @api public
*/
exports.get = function(obj, path) {
var segs = path.split('.');
var attr = segs.pop();
for (var i = 0; i < segs.length; i++) {
var seg = segs[i];
if (!obj[seg]) return;
obj = obj[seg];
}
return obj[attr];
};
/**
* Delete given `path`
*
* @param {Object} obj
* @param {String} path
* @return {Mixed}
* @api public
*/
exports.delete = function(obj, path) {
var segs = path.split('.');
var attr = segs.pop();
for (var i = 0; i < segs.length; i++) {
var seg = segs[i];
if (!obj[seg]) return;
if (!isSafe(obj, seg)) return;
obj = obj[seg];
}
if (!isSafe(obj, attr)) return;
if (Array.isArray(obj)) {
obj.splice(attr, 1);
} else {
delete obj[attr];
}
};
function isSafe(obj, prop) {
if (isObject(obj)) {
return obj[prop] === undefined || hasOwnProperty(obj, prop);
}
if (Array.isArray(obj)) {
return !isNaN(parseInt(prop, 10));
}
return false;
}
function hasOwnProperty(obj, prop) {
return Object.prototype.hasOwnProperty.call(obj, prop);
}
function isObject(obj) {
return Object.prototype.toString.call(obj) === '[object Object]';
}