StringToNumber.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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('../helpers/regexTester');
  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. // whitespace from: https://es5.github.io/#x15.5.4.20
  17. // implementation from https://github.com/es-shims/es5-shim/blob/v3.4.0/es5-shim.js#L1304-L1324
  18. var ws = [
  19. '\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003',
  20. '\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028',
  21. '\u2029\uFEFF'
  22. ].join('');
  23. var trimRegex = new RegExp('(^[' + ws + ']+)|([' + ws + ']+$)', 'g');
  24. var $replace = callBound('String.prototype.replace');
  25. var $trim = function (value) {
  26. return $replace(value, trimRegex, '');
  27. };
  28. var Type = require('./Type');
  29. // https://ecma-international.org/ecma-262/13.0/#sec-stringtonumber
  30. module.exports = function StringToNumber(argument) {
  31. if (Type(argument) !== 'String') {
  32. throw new $TypeError('Conversion from \'BigInt\' to \'number\' is not allowed.');
  33. }
  34. if (isBinary(argument)) {
  35. return $Number($parseInteger($strSlice(argument, 2), 2));
  36. }
  37. if (isOctal(argument)) {
  38. return $Number($parseInteger($strSlice(argument, 2), 8));
  39. }
  40. if (hasNonWS(argument) || isInvalidHexLiteral(argument)) {
  41. return NaN;
  42. }
  43. var trimmed = $trim(argument);
  44. if (trimmed !== argument) {
  45. return StringToNumber(trimmed);
  46. }
  47. return $Number(argument);
  48. };