ToNumber.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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 === 'string') {
  37. if (isBinary(value)) {
  38. return ToNumber($parseInteger($strSlice(value, 2), 2));
  39. } else if (isOctal(value)) {
  40. return ToNumber($parseInteger($strSlice(value, 2), 8));
  41. } else if (hasNonWS(value) || isInvalidHexLiteral(value)) {
  42. return NaN;
  43. } else {
  44. var trimmed = $trim(value);
  45. if (trimmed !== value) {
  46. return ToNumber(trimmed);
  47. }
  48. }
  49. }
  50. return $Number(value);
  51. };