-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
46 lines (37 loc) · 1.09 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
var util = require('util');
module.exports = function safe(obj) {
var target = isObject(obj) ? obj : function() {};
return new Proxy(target, {
get: function(receiver, name) {
if (name === util.inspect.custom) {
return function(depth, options) {
var padding = ' '.repeat('safe( '.length);
var inner = util.inspect(obj, options).replace(/\n/g, '\n' + padding);
return options.stylize('safe', 'special') + '( ' + inner + ' )';
}
}
if (name === '__value') {
return obj;
}
if (obj == null) {
return safe(undefined);
}
if (isFunction(obj[name])) {
return safe(obj[name].bind(obj));
}
return safe(obj[name]);
},
apply: function(target, thisObj, args) {
var fnResult = isFunction(obj) ?
obj.apply(thisObj, args) : undefined;
return safe(fnResult);
}
});
};
var isFunction = function(obj) {
return typeof obj === 'function';
};
var isObject = function(obj) {
var type = typeof obj;
return type === 'function' || type === 'object' && !!obj;
};