ToBigInt.js 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  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. // https://262.ecma-international.org/13.0/#sec-tobigint
  10. module.exports = function ToBigInt(argument) {
  11. if (!$BigInt) {
  12. throw new $SyntaxError('BigInts are not supported in this environment');
  13. }
  14. var prim = ToPrimitive(argument, $Number);
  15. if (prim == null) {
  16. throw new $TypeError('Cannot convert null or undefined to a BigInt');
  17. }
  18. if (typeof prim === 'boolean') {
  19. return prim ? $BigInt(1) : $BigInt(0);
  20. }
  21. if (typeof prim === 'number') {
  22. throw new $TypeError('Cannot convert a Number value to a BigInt');
  23. }
  24. if (typeof prim === 'string') {
  25. var n = StringToBigInt(prim);
  26. if (typeof n === 'undefined') {
  27. throw new $TypeError('Failed to parse String to BigInt');
  28. }
  29. return n;
  30. }
  31. if (typeof prim === 'symbol') {
  32. throw new $TypeError('Cannot convert a Symbol value to a BigInt');
  33. }
  34. if (typeof prim !== 'bigint') {
  35. throw new $SyntaxError('Assertion failed: unknown primitive type');
  36. }
  37. return prim;
  38. };