StringToNumber.js 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. 'use strict';
  2. var GetIntrinsic = require('get-intrinsic');
  3. var $Number = GetIntrinsic('%Number%');
  4. var $RegExp = GetIntrinsic('%RegExp%');
  5. var $TypeError = GetIntrinsic('%TypeError%');
  6. var $parseInteger = GetIntrinsic('%parseInt%');
  7. var callBound = require('call-bind/callBound');
  8. var regexTester = require('safe-regex-test');
  9. var $strSlice = callBound('String.prototype.slice');
  10. var isBinary = regexTester(/^0b[01]+$/i);
  11. var isOctal = regexTester(/^0o[0-7]+$/i);
  12. var isInvalidHexLiteral = regexTester(/^[-+]0x[0-9a-f]+$/i);
  13. var nonWS = ['\u0085', '\u200b', '\ufffe'].join('');
  14. var nonWSregex = new $RegExp('[' + nonWS + ']', 'g');
  15. var hasNonWS = regexTester(nonWSregex);
  16. var $trim = require('string.prototype.trim');
  17. var Type = require('./Type');
  18. // https://262.ecma-international.org/13.0/#sec-stringtonumber
  19. module.exports = function StringToNumber(argument) {
  20. if (Type(argument) !== 'String') {
  21. throw new $TypeError('Assertion failed: `argument` is not a String');
  22. }
  23. if (isBinary(argument)) {
  24. return $Number($parseInteger($strSlice(argument, 2), 2));
  25. }
  26. if (isOctal(argument)) {
  27. return $Number($parseInteger($strSlice(argument, 2), 8));
  28. }
  29. if (hasNonWS(argument) || isInvalidHexLiteral(argument)) {
  30. return NaN;
  31. }
  32. var trimmed = $trim(argument);
  33. if (trimmed !== argument) {
  34. return StringToNumber(trimmed);
  35. }
  36. return $Number(argument);
  37. };