esnext.number.from-string.js 1.1 KB

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