Browse Source

util: Format negative zero as '-0'

Format negative zero as '-0' instead of as '0', as it does not behave
identically to positive zero. ((-0).toString() still returns '0' as
required by ES5 9.8.1.2).

Fixes joyent/node#6548.
Closes joyent/node#6550.
v0.11.10-release
David Chan 11 years ago
committed by Nathan Rajlich
parent
commit
b3e4fc6a48
  1. 7
      lib/util.js
  2. 4
      test/simple/test-util-inspect.js

7
lib/util.js

@ -323,8 +323,13 @@ function formatPrimitive(ctx, value) {
.replace(/\\"/g, '"') + '\'';
return ctx.stylize(simple, 'string');
}
if (isNumber(value))
if (isNumber(value)) {
// Format -0 as '-0'. Strict equality won't distinguish 0 from -0,
// so instead we use the fact that 1 / -0 < 0 whereas 1 / 0 > 0 .
if (value === 0 && 1 / value < 0)
return ctx.stylize('-0', 'number');
return ctx.stylize('' + value, 'number');
}
if (isBoolean(value))
return ctx.stylize('' + value, 'boolean');
// For some reason typeof null is "object", so special case here.

4
test/simple/test-util-inspect.js

@ -34,6 +34,10 @@ Date2.prototype.foo = 'bar';
var after = util.inspect(d);
assert.equal(orig, after);
// test positive/negative zero
assert.equal(util.inspect(0), '0');
assert.equal(util.inspect(-0), '-0');
// test for sparse array
var a = ['foo', 'bar', 'baz'];
assert.equal(util.inspect(a), '[ \'foo\', \'bar\', \'baz\' ]');

Loading…
Cancel
Save