forked from mantacode/safe-obj
/
safe.js
106 lines (91 loc) · 2.55 KB
/
safe.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
100
101
102
103
104
105
106
;(function(self) {
self.ILLEGAL_KEYS = ["constructor", "__proto__", "prototype"];
self.isIllegalKey = function (key) {
return self.ILLEGAL_KEYS.indexOf(key) !== -1;
}
self.isProtoPath = function (path) {
return Array.isArray(path)
? path.some(self.isIllegalKey)
: typeof path === "string"
? self.isIllegalKey(path)
: false;
}
self.disallowProtoPath = function (path) {
if (self.isProtoPath(path)) {
throw new Error("Unsafe path encountered: " + path)
}
}
self.safe = function (obj, path, otherwise) {
obj = isObject(obj) ? obj : {};
var props = path.split('.');
if (props.length === 1) {
return typeof obj[props[0]] === 'undefined' ? otherwise : obj[props.shift()];
} else {
var prop = props.shift();
return isObject(obj) ? self.safe(obj[prop], props.join('.'), otherwise) : otherwise;
}
};
self.expand = function (obj, path, thing) {
obj = isObject(obj) ? obj : {};
var props = path.split('.');
self.disallowProtoPath(props);
if (props.length === 1) {
obj[props.shift()] = thing;
} else {
var prop = props.shift();
if (!(prop in obj)) {
obj[prop] = {};
}
self.expand(obj[prop], props.join('.'), thing);
}
};
self.allOf = function(obj, paths) {
if (!isArray(arguments[1])) {
paths = [].slice.call(arguments);
obj = paths.shift();
}
if (isObject(obj)) {
return every(paths, function(path) {
return !!self.safe(obj, path);
});
}
};
self.anyOf = function (obj, paths) {
if (!isArray(arguments[1])) {
paths = [].slice.call(arguments);
obj = paths.shift();
}
if (isObject(obj)) {
return any(paths, function(path) {
return !!self.safe(obj, path);
});
} else {
return false;
}
};
self.noneOf = function() {
return !self.anyOf.apply(self, arguments);
};
var isObject = function (obj) {
return (typeof obj === 'object' || typeof obj === 'function') && obj !== null;
};
var isArray = function (arr) {
return arr instanceof Array && arr.splice;
};
var any = function (arr, fn) {
var pass = false;
for (var i = 0; i < arr.length; i++) {
if (fn(arr[i])) {
pass = true;
}
}
return pass;
};
var every = function (arr, fn) {
var pass = false;
for (var i = 0; i < arr.length; i++) {
pass = fn(arr[i]);
}
return pass;
};
})(typeof module !== 'undefined' ? module.exports : (typeof window !== 'undefined' ? window.safe = {} : this));