You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

33 lines
783 B
JavaScript

/**
* Check circular references.
*
* @param ref A function that returns an alternative reference.
* @param methods A boolean that indicates functions should be
* coerced to strings.
*/
function circular(ref, methods) {
ref = ref || '[Circular]';
var seen = [];
return function (key, val) {
if(typeof val === 'function' && methods) {
val = val.toString();
}
if(!val || typeof (val) !== 'object') {
return val;
}
if(~seen.indexOf(val)) {
if(typeof ref === 'function') return ref(val);
return ref;
}
seen.push(val);
return val;
};
}
function stringify(obj, indent, ref, methods) {
return JSON.stringify(obj, circular(ref, methods), indent);
}
module.exports = circular;
module.exports.stringify = stringify;