esnext.number.from-string.js 1.5 KB

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