Skip to content

Commit

Permalink
Fix #2109: stringify should handle objects with non-coercible length
Browse files Browse the repository at this point in the history
Root cause is that some JS objects cannot be coerced to a Number:

Number({toString: 0});
TypeError: can't convert ({toString:0}) to number
Number({a: 0});
NaN
  • Loading branch information
Josh Lory committed Feb 16, 2016
1 parent 2a85944 commit 0627fa0
Show file tree
Hide file tree
Showing 2 changed files with 5 additions and 1 deletion.
2 changes: 1 addition & 1 deletion lib/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -454,7 +454,7 @@ function jsonStringify(object, spaces, depth) {
var space = spaces * depth;
var str = isArray(object) ? '[' : '{';
var end = isArray(object) ? ']' : '}';
var length = object.length || exports.keys(object).length;
var length = typeof object.length === 'number' ? object.length : exports.keys(object).length;
// `.repeat()` polyfill
function repeat(s, n) {
return new Array(n).join(s);
Expand Down
4 changes: 4 additions & 0 deletions test/acceptance/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -331,6 +331,10 @@ describe('lib/utils', function () {

stringify(a).should.equal('{\n "foo": 1\n}');
});

it('should handle length properties that cannot be coerced to a number', function () {
stringify({length: {toString: 0}}).should.equal('{\n "length": {\n "toString": 0\n }\n}');
});
});

describe('type', function () {
Expand Down

0 comments on commit 0627fa0

Please sign in to comment.