Node-Red configuration
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

esnext.number.from-string.js 1.7KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  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 INVALID_NUMBER_REPRESENTATION = 'Invalid number representation';
  6. var INVALID_RADIX = 'Invalid radix';
  7. var $RangeError = RangeError;
  8. var $SyntaxError = SyntaxError;
  9. var $TypeError = TypeError;
  10. var $parseInt = parseInt;
  11. var pow = Math.pow;
  12. var valid = /^[\d.a-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. var split = uncurryThis(''.split);
  18. // `Number.fromString` method
  19. // https://github.com/tc39/proposal-number-fromstring
  20. $({ target: 'Number', stat: true, forced: true }, {
  21. fromString: function fromString(string, radix) {
  22. var sign = 1;
  23. if (typeof string != 'string') throw new $TypeError(INVALID_NUMBER_REPRESENTATION);
  24. if (!string.length) throw new $SyntaxError(INVALID_NUMBER_REPRESENTATION);
  25. if (charAt(string, 0) === '-') {
  26. sign = -1;
  27. string = stringSlice(string, 1);
  28. if (!string.length) throw new $SyntaxError(INVALID_NUMBER_REPRESENTATION);
  29. }
  30. var R = radix === undefined ? 10 : toIntegerOrInfinity(radix);
  31. if (R < 2 || R > 36) throw new $RangeError(INVALID_RADIX);
  32. if (!exec(valid, string)) throw new $SyntaxError(INVALID_NUMBER_REPRESENTATION);
  33. var parts = split(string, '.');
  34. var mathNum = $parseInt(parts[0], R);
  35. if (parts.length > 1) mathNum += $parseInt(parts[1], R) / pow(R, parts[1].length);
  36. if (R === 10 && numberToString(mathNum, R) !== string) throw new $SyntaxError(INVALID_NUMBER_REPRESENTATION);
  37. return sign * mathNum;
  38. }
  39. });