Skip to content

Commit

Permalink
[Fix] ES2020+: ToBigInt: properly throw on anything besides strin…
Browse files Browse the repository at this point in the history
…g, bigint, boolean
  • Loading branch information
ljharb committed Mar 8, 2023
1 parent 7131d78 commit 0a4dcb2
Show file tree
Hide file tree
Showing 4 changed files with 100 additions and 19 deletions.
34 changes: 31 additions & 3 deletions 2020/ToBigInt.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,15 @@
var GetIntrinsic = require('get-intrinsic');

var $BigInt = GetIntrinsic('%BigInt%', true);
var $asIntN = GetIntrinsic('%BigInt.asIntN%', true);
var $Number = GetIntrinsic('%Number%');
var $TypeError = GetIntrinsic('%TypeError%');
var $SyntaxError = GetIntrinsic('%SyntaxError%');

var StringToBigInt = require('./StringToBigInt');
var ToPrimitive = require('./ToPrimitive');

var isNaN = require('../helpers/isNaN');

// https://262.ecma-international.org/11.0/#sec-tobigint

module.exports = function ToBigInt(argument) {
Expand All @@ -18,8 +21,33 @@ module.exports = function ToBigInt(argument) {

var prim = ToPrimitive(argument, $Number);

if (prim == null) {
throw new $TypeError('Cannot convert null or undefined to a BigInt');
}

if (typeof prim === 'boolean') {
return prim ? $BigInt(1) : $BigInt(0);
}

if (typeof prim === 'number') {
return $asIntN(0, prim);
throw new $TypeError('Cannot convert a Number value to a BigInt');
}

if (typeof prim === 'string') {
var n = StringToBigInt(prim);
if (isNaN(n)) {
throw new $TypeError('Failed to parse String to BigInt');
}
return n;
}

if (typeof prim === 'symbol') {
throw new $TypeError('Cannot convert a Symbol value to a BigInt');
}
return $BigInt(prim);

if (typeof prim !== 'bigint') {
throw new $SyntaxError('Assertion failed: unknown primitive type');
}

return prim;
};
34 changes: 31 additions & 3 deletions 2021/ToBigInt.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

34 changes: 31 additions & 3 deletions 2022/ToBigInt.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

17 changes: 7 additions & 10 deletions test/tests.js
Original file line number Diff line number Diff line change
Expand Up @@ -10754,16 +10754,13 @@ var es2020 = function ES2020(ES, ops, expectedMissing, skips) {
});

test('ToBigInt', function (t) {
t['throws'](
function () { ES.ToBigInt(); },
hasBigInts ? TypeError : SyntaxError,
'undefined throws'
);
t['throws'](
function () { ES.ToBigInt(null); },
hasBigInts ? TypeError : SyntaxError,
'null throws'
);
forEach([null, undefined].concat(v.symbols, v.numbers), function (nonBigIntCoercible) {
t['throws'](
function () { ES.ToBigInt(nonBigIntCoercible); },
hasBigInts ? TypeError : SyntaxError,
debug(nonBigIntCoercible) + ' throws'
);
});

forEach(v.symbols, function (sym) {
t['throws'](
Expand Down

0 comments on commit 0a4dcb2

Please sign in to comment.