esnext.number.from-string.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. 'use strict';
  2. var $ = require('../internals/export');
  3. var global = require('../internals/global');
  4. var uncurryThis = require('../internals/function-uncurry-this');
  5. var toIntegerOrInfinity = require('../internals/to-integer-or-infinity');
  6. var parseInt = require('../internals/number-parse-int');
  7. var INVALID_NUMBER_REPRESENTATION = 'Invalid number representation';
  8. var INVALID_RADIX = 'Invalid radix';
  9. var RangeError = global.RangeError;
  10. var SyntaxError = global.SyntaxError;
  11. var TypeError = global.TypeError;
  12. var valid = /^[\da-z]+$/;
  13. var charAt = uncurryThis(''.charAt);
  14. var exec = uncurryThis(valid.exec);
  15. var numberToString = uncurryThis(1.0.toString);
  16. var stringSlice = uncurryThis(''.slice);
  17. // `Number.fromString` method
  18. // https://github.com/tc39/proposal-number-fromstring
  19. $({ target: 'Number', stat: true, forced: true }, {
  20. fromString: function fromString(string, radix) {
  21. var sign = 1;
  22. var R, mathNum;
  23. if (typeof string != 'string') throw TypeError(INVALID_NUMBER_REPRESENTATION);
  24. if (!string.length) throw SyntaxError(INVALID_NUMBER_REPRESENTATION);
  25. if (charAt(string, 0) == '-') {
  26. sign = -1;
  27. string = stringSlice(string, 1);
  28. if (!string.length) throw SyntaxError(INVALID_NUMBER_REPRESENTATION);
  29. }
  30. R = radix === undefined ? 10 : toIntegerOrInfinity(radix);
  31. if (R < 2 || R > 36) throw RangeError(INVALID_RADIX);
  32. if (!exec(valid, string) || numberToString(mathNum = parseInt(string, R), R) !== string) {
  33. throw SyntaxError(INVALID_NUMBER_REPRESENTATION);
  34. }
  35. return sign * mathNum;
  36. }
  37. });