ToBigInt.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. 'use strict';
  2. var GetIntrinsic = require('get-intrinsic');
  3. var $BigInt = GetIntrinsic('%BigInt%', true);
  4. var $Number = GetIntrinsic('%Number%');
  5. var $TypeError = require('es-errors/type');
  6. var $SyntaxError = require('es-errors/syntax');
  7. var StringToBigInt = require('./StringToBigInt');
  8. var ToPrimitive = require('./ToPrimitive');
  9. var isNaN = require('../helpers/isNaN');
  10. // https://262.ecma-international.org/11.0/#sec-tobigint
  11. module.exports = function ToBigInt(argument) {
  12. if (!$BigInt) {
  13. throw new $SyntaxError('BigInts are not supported in this environment');
  14. }
  15. var prim = ToPrimitive(argument, $Number);
  16. if (prim == null) {
  17. throw new $TypeError('Cannot convert null or undefined to a BigInt');
  18. }
  19. if (typeof prim === 'boolean') {
  20. return prim ? $BigInt(1) : $BigInt(0);
  21. }
  22. if (typeof prim === 'number') {
  23. throw new $TypeError('Cannot convert a Number value to a BigInt');
  24. }
  25. if (typeof prim === 'string') {
  26. var n = StringToBigInt(prim);
  27. if (isNaN(n)) {
  28. throw new $TypeError('Failed to parse String to BigInt');
  29. }
  30. return n;
  31. }
  32. if (typeof prim === 'symbol') {
  33. throw new $TypeError('Cannot convert a Symbol value to a BigInt');
  34. }
  35. if (typeof prim !== 'bigint') {
  36. throw new $SyntaxError('Assertion failed: unknown primitive type');
  37. }
  38. return prim;
  39. };