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 17, 2016
1 parent 0543798 commit 3b92fcc
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 @@ -340,6 +340,10 @@ describe('lib/utils', function () {
stringify({symbol: symbol}).should.equal('{\n "symbol": Symbol(value)\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 3b92fcc

Please sign in to comment.