Skip to content

Commit

Permalink
Add support for binary and octal literals in strings to the Number
Browse files Browse the repository at this point in the history
…constructor.

Fixes #358.
  • Loading branch information
ljharb committed Aug 15, 2015
1 parent 95ccec5 commit 73598be
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 0 deletions.
43 changes: 43 additions & 0 deletions es6-shim.js
Expand Up @@ -1132,6 +1132,49 @@
}, true);
}

if (Number('0o10') !== 8 || Number('0b10') !== 2) {
var OrigNumber = Number;
var isBinary = Function.bind.call(Function.call, RegExp.prototype.test, /^0b/i);
var isOctal = Function.bind.call(Function.call, RegExp.prototype.test, /^0o/i);
var toPrimitive = function (O) { // need to replace this with `es-to-primitive/es6`
var result;
if (typeof O.valueOf === 'function') {
result = O.valueOf();
if (Type.primitive(result)) {
return result;
}
}
if (typeof O.toString === 'function') {
result = O.toString();
if (Type.primitive(result)) {
return result;
}
}
throw new TypeError('No default value');
};
var NumberShim = function Number(value) {
var primValue = Type.primitive(value) ? value : toPrimitive(value, 'number');
if (typeof primValue === 'string') {
if (isBinary(primValue)) {
primValue = parseInt(_strSlice(primValue, 2), 2);
} else if (isOctal(primValue)) {
primValue = parseInt(_strSlice(primValue, 2), 8);
}
}
if (this instanceof Number) {
return new OrigNumber(primValue);
}
/* jshint newcap: false */
return OrigNumber(primValue);
/* jshint newcap: true */
};
wrapConstructor(OrigNumber, NumberShim, {});
/*globals Number: true */
Number = NumberShim;
Value.redefine(globals, 'Number', NumberShim);
/*globals Number: false */
}

var maxSafeInteger = Math.pow(2, 53) - 1;
defineProperties(Number, {
MAX_SAFE_INTEGER: maxSafeInteger,
Expand Down
14 changes: 14 additions & 0 deletions test/number.js
Expand Up @@ -354,5 +354,19 @@ describe('Number', function () {
expect(+a).to.equal(0xA);
expect(a instanceof Number).to.equal(true);
});

it('works with binary literals in string form', function () {
expect(Number('0b1')).to.equal(1);
expect(Number('0b10')).to.equal(2);
expect(Number('0b11')).to.equal(3);
expect(Number({ toString: function () { return '0b100'; }, valueOf: function () { return '0b101'; } })).to.equal(5);
});

it('works with octal literals in string form', function () {
expect(Number('0o7')).to.equal(7);
expect(Number('0o10')).to.equal(8);
expect(Number('0o11')).to.equal(9);
expect(Number({ toString: function () { return '0o12'; }, valueOf: function () { return '0o13'; } })).to.equal(11);
});
});
});

0 comments on commit 73598be

Please sign in to comment.