ToNumber.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  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('safe-regex-test');
  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. var $trim = require('string.prototype.trim');
  18. var ToPrimitive = require('./ToPrimitive');
  19. // https://262.ecma-international.org/6.0/#sec-tonumber
  20. module.exports = function ToNumber(argument) {
  21. var value = isPrimitive(argument) ? argument : ToPrimitive(argument, $Number);
  22. if (typeof value === 'symbol') {
  23. throw new $TypeError('Cannot convert a Symbol value to a number');
  24. }
  25. if (typeof value === 'string') {
  26. if (isBinary(value)) {
  27. return ToNumber($parseInteger($strSlice(value, 2), 2));
  28. } else if (isOctal(value)) {
  29. return ToNumber($parseInteger($strSlice(value, 2), 8));
  30. } else if (hasNonWS(value) || isInvalidHexLiteral(value)) {
  31. return NaN;
  32. }
  33. var trimmed = $trim(value);
  34. if (trimmed !== value) {
  35. return ToNumber(trimmed);
  36. }
  37. }
  38. return $Number(value);
  39. };