ToNumber.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. 'use strict';
  2. var GetIntrinsic = require('get-intrinsic');
  3. var $TypeError = GetIntrinsic('%TypeError%');
  4. var $Number = GetIntrinsic('%Number%');
  5. var $RegExp = GetIntrinsic('%RegExp%');
  6. var $parseInteger = GetIntrinsic('%parseInt%');
  7. var callBound = require('call-bind/callBound');
  8. var regexTester = require('../helpers/regexTester');
  9. var isPrimitive = require('../helpers/isPrimitive');
  10. var $strSlice = callBound('String.prototype.slice');
  11. var isBinary = regexTester(/^0b[01]+$/i);
  12. var isOctal = regexTester(/^0o[0-7]+$/i);
  13. var isInvalidHexLiteral = regexTester(/^[-+]0x[0-9a-f]+$/i);
  14. var nonWS = ['\u0085', '\u200b', '\ufffe'].join('');
  15. var nonWSregex = new $RegExp('[' + nonWS + ']', 'g');
  16. var hasNonWS = regexTester(nonWSregex);
  17. // whitespace from: https://es5.github.io/#x15.5.4.20
  18. // implementation from https://github.com/es-shims/es5-shim/blob/v3.4.0/es5-shim.js#L1304-L1324
  19. var ws = [
  20. '\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003',
  21. '\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028',
  22. '\u2029\uFEFF'
  23. ].join('');
  24. var trimRegex = new RegExp('(^[' + ws + ']+)|([' + ws + ']+$)', 'g');
  25. var $replace = callBound('String.prototype.replace');
  26. var $trim = function (value) {
  27. return $replace(value, trimRegex, '');
  28. };
  29. var ToPrimitive = require('./ToPrimitive');
  30. // https://ecma-international.org/ecma-262/6.0/#sec-tonumber
  31. module.exports = function ToNumber(argument) {
  32. var value = isPrimitive(argument) ? argument : ToPrimitive(argument, $Number);
  33. if (typeof value === 'symbol') {
  34. throw new $TypeError('Cannot convert a Symbol value to a number');
  35. }
  36. if (typeof value === 'bigint') {
  37. throw new $TypeError('Conversion from \'BigInt\' to \'number\' is not allowed.');
  38. }
  39. if (typeof value === 'string') {
  40. if (isBinary(value)) {
  41. return ToNumber($parseInteger($strSlice(value, 2), 2));
  42. } else if (isOctal(value)) {
  43. return ToNumber($parseInteger($strSlice(value, 2), 8));
  44. } else if (hasNonWS(value) || isInvalidHexLiteral(value)) {
  45. return NaN;
  46. }
  47. var trimmed = $trim(value);
  48. if (trimmed !== value) {
  49. return ToNumber(trimmed);
  50. }
  51. }
  52. return $Number(value);
  53. };