StringToNumber.js 1.2 KB

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