undefsafe.js
2.53 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
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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
'use strict';
function undefsafe(obj, path, value, __res) {
// I'm not super keen on this private function, but it's because
// it'll also be use in the browser and I wont *one* function exposed
function split(path) {
var res = [];
var level = 0;
var key = '';
for (var i = 0; i < path.length; i++) {
var c = path.substr(i, 1);
if (level === 0 && (c === '.' || c === '[')) {
if (c === '[') {
level++;
i++;
c = path.substr(i, 1);
}
if (key) {
// the first value could be a string
res.push(key);
}
key = '';
continue;
}
if (c === ']') {
level--;
key = key.slice(0, -1);
continue;
}
key += c;
}
res.push(key);
return res;
}
// bail if there's nothing
if (obj === undefined || obj === null) {
return undefined;
}
var parts = split(path);
var key = null;
var type = typeof obj;
var root = obj;
var parent = obj;
var star =
parts.filter(function(_) {
return _ === '*';
}).length > 0;
// we're dealing with a primitive
if (type !== 'object' && type !== 'function') {
return obj;
} else if (path.trim() === '') {
return obj;
}
key = parts[0];
var i = 0;
for (; i < parts.length; i++) {
key = parts[i];
parent = obj;
if (key === '*') {
// loop through each property
var prop = '';
var res = __res || [];
for (prop in parent) {
var shallowObj = undefsafe(
obj[prop],
parts.slice(i + 1).join('.'),
value,
res
);
if (shallowObj && shallowObj !== res) {
if ((value && shallowObj === value) || value === undefined) {
if (value !== undefined) {
return shallowObj;
}
res.push(shallowObj);
}
}
}
if (res.length === 0) {
return undefined;
}
return res;
}
if (Object.getOwnPropertyNames(obj).indexOf(key) == -1) {
return undefined;
}
obj = obj[key];
if (obj === undefined || obj === null) {
break;
}
}
// if we have a null object, make sure it's the one the user was after,
// if it's not (i.e. parts has a length) then give undefined back.
if (obj === null && i !== parts.length - 1) {
obj = undefined;
} else if (!star && value) {
key = path.split('.').pop();
parent[key] = value;
}
return obj;
}
if (typeof module !== 'undefined') {
module.exports = undefsafe;
}