Skip to content

Commit

Permalink
circular example
Browse files Browse the repository at this point in the history
  • Loading branch information
James Halliday committed Jul 26, 2013
1 parent 34be6b6 commit 4b4a7b9
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 7 deletions.
4 changes: 4 additions & 0 deletions example/circular.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
var inspect = require('../');
var obj = { a: 1, b: [3,4] };
obj.c = obj;
console.log(inspect(obj));
23 changes: 16 additions & 7 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,21 @@
module.exports = function inspect_ (obj, opts, depth) {
module.exports = function inspect_ (obj, opts, depth, seen) {
if (!opts) opts = {};
var maxDepth = opts.depth || 5;

var maxDepth = opts.depth || 5;
if (depth === undefined) depth = 0;
if (depth > maxDepth) return '...';

function inspect (value) {
return inspect_(value, opts, depth + 1);
if (seen === undefined) seen = [];
else if (seen.indexOf(obj) >= 0) {
return '[Circular]';
}

function inspect (value, from) {
if (from) {
seen = seen.slice();
seen.push(from);
}
return inspect_(value, opts, depth + 1, seen);
}

if (typeof obj === 'string') {
Expand All @@ -26,7 +35,7 @@ module.exports = function inspect_ (obj, opts, depth) {
else if (isArray(obj)) {
var xs = Array(obj.length);
for (var i = 0; i < obj.length; i++) {
xs[i] = inspect(obj[i]);
xs[i] = inspect(obj[i], obj);
}
return '[ ' + xs.join(', ') + ' ]';
}
Expand All @@ -35,9 +44,9 @@ module.exports = function inspect_ (obj, opts, depth) {
for (var key in obj) {
if ({}.hasOwnProperty.call(obj, key)) {
if (/[^\w$]/.test(key)) {
xs.push(inspect(key) + ': ' + inspect(obj[key]));
xs.push(inspect(key) + ': ' + inspect(obj[key], obj));
}
else xs.push(key + ': ' + inspect(obj[key]));
else xs.push(key + ': ' + inspect(obj[key], obj));
}
}
return '{ ' + xs.join(', ') + ' }';
Expand Down

0 comments on commit 4b4a7b9

Please sign in to comment.