-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathindex.js
65 lines (53 loc) · 1.32 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
var hasProp = Object.prototype.hasOwnProperty;
function throwsMessage(err) {
return '[Throws: ' + (err ? err.message : '?') + ']';
}
function safeGetValueFromPropertyOnObject(obj, property) {
if (hasProp.call(obj, property)) {
try {
return obj[property];
}
catch (err) {
return throwsMessage(err);
}
}
return obj[property];
}
function ensureProperties(obj) {
var seen = [ ]; // store references to objects we have seen before
function visit(obj) {
if (obj === null || typeof obj !== 'object') {
return obj;
}
if (seen.indexOf(obj) !== -1) {
return '[Circular]';
}
seen.push(obj);
if (typeof obj.toJSON === 'function') {
try {
var fResult = visit(obj.toJSON());
seen.pop();
return fResult;
} catch(err) {
return throwsMessage(err);
}
}
if (Array.isArray(obj)) {
var aResult = obj.map(visit);
seen.pop();
return aResult;
}
var result = Object.keys(obj).reduce(function(result, prop) {
// prevent faulty defined getter properties
result[prop] = visit(safeGetValueFromPropertyOnObject(obj, prop));
return result;
}, {});
seen.pop();
return result;
};
return visit(obj);
}
module.exports = function(data, replacer, space) {
return JSON.stringify(ensureProperties(data), replacer, space);
}
module.exports.ensureProperties = ensureProperties;