Skip to content
This repository has been archived by the owner on Apr 22, 2023. It is now read-only.

Commit

Permalink
util: Fix inspection for sparse array
Browse files Browse the repository at this point in the history
Fixes #1651.
  • Loading branch information
koichik committed Sep 8, 2011
1 parent 98b6442 commit 6139459
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 4 deletions.
33 changes: 29 additions & 4 deletions lib/util.js
Expand Up @@ -211,7 +211,7 @@ function formatValue(ctx, value, recurseTimes) {
base = ' ' + value.toUTCString(); base = ' ' + value.toUTCString();
} }


if (keys.length === 0) { if (keys.length === 0 && (!array || value.length == 0)) {
return braces[0] + base + braces[1]; return braces[0] + base + braces[1];
} }


Expand All @@ -225,9 +225,14 @@ function formatValue(ctx, value, recurseTimes) {


ctx.seen.push(value); ctx.seen.push(value);


var output = keys.map(function(key) { var output;
return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); if (array) {
}); output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
} else {
output = keys.map(function(key) {
return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
});
}


ctx.seen.pop(); ctx.seen.pop();


Expand Down Expand Up @@ -259,6 +264,26 @@ function formatPrimitive(ctx, value) {
} }




function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
var output = [];
for (var i = 0, l = value.length; i < l; ++i) {
if (Object.prototype.hasOwnProperty.call(value, String(i))) {
output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
String(i), true));
} else {
output.push('');
}
}
keys.forEach(function(key) {
if (!key.match(/^\d+$/)) {
output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
key, true));
}
});
return output;
}


function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
var name, str; var name, str;
if (value.__lookupGetter__) { if (value.__lookupGetter__) {
Expand Down
8 changes: 8 additions & 0 deletions test/simple/test-util-inspect.js
Expand Up @@ -33,3 +33,11 @@ var orig = util.inspect(d);
Date2.prototype.foo = 'bar'; Date2.prototype.foo = 'bar';
var after = util.inspect(d); var after = util.inspect(d);
assert.equal(orig, after); assert.equal(orig, after);

// test for sparse array
var a = [ 'foo', 'bar', 'baz' ];
assert.equal(util.inspect(a), "[ 'foo', 'bar', 'baz' ]");
delete a[1];
assert.equal(util.inspect(a), "[ 'foo', , 'baz' ]");
assert.equal(util.inspect(a, true), "[ 'foo', , 'baz', [length]: 3 ]");
assert.equal(util.inspect(new Array(5)), '[ , , , , ]');

0 comments on commit 6139459

Please sign in to comment.