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.
42 lines
1.7 KiB
42 lines
1.7 KiB
3 weeks ago
|
'use strict';
|
||
|
var $ = require('../internals/export');
|
||
|
var uncurryThis = require('../internals/function-uncurry-this');
|
||
|
var toIntegerOrInfinity = require('../internals/to-integer-or-infinity');
|
||
|
|
||
|
var INVALID_NUMBER_REPRESENTATION = 'Invalid number representation';
|
||
|
var INVALID_RADIX = 'Invalid radix';
|
||
|
var $RangeError = RangeError;
|
||
|
var $SyntaxError = SyntaxError;
|
||
|
var $TypeError = TypeError;
|
||
|
var $parseInt = parseInt;
|
||
|
var pow = Math.pow;
|
||
|
var valid = /^[\d.a-z]+$/;
|
||
|
var charAt = uncurryThis(''.charAt);
|
||
|
var exec = uncurryThis(valid.exec);
|
||
|
var numberToString = uncurryThis(1.0.toString);
|
||
|
var stringSlice = uncurryThis(''.slice);
|
||
|
var split = uncurryThis(''.split);
|
||
|
|
||
|
// `Number.fromString` method
|
||
|
// https://github.com/tc39/proposal-number-fromstring
|
||
|
$({ target: 'Number', stat: true, forced: true }, {
|
||
|
fromString: function fromString(string, radix) {
|
||
|
var sign = 1;
|
||
|
if (typeof string != 'string') throw new $TypeError(INVALID_NUMBER_REPRESENTATION);
|
||
|
if (!string.length) throw new $SyntaxError(INVALID_NUMBER_REPRESENTATION);
|
||
|
if (charAt(string, 0) === '-') {
|
||
|
sign = -1;
|
||
|
string = stringSlice(string, 1);
|
||
|
if (!string.length) throw new $SyntaxError(INVALID_NUMBER_REPRESENTATION);
|
||
|
}
|
||
|
var R = radix === undefined ? 10 : toIntegerOrInfinity(radix);
|
||
|
if (R < 2 || R > 36) throw new $RangeError(INVALID_RADIX);
|
||
|
if (!exec(valid, string)) throw new $SyntaxError(INVALID_NUMBER_REPRESENTATION);
|
||
|
var parts = split(string, '.');
|
||
|
var mathNum = $parseInt(parts[0], R);
|
||
|
if (parts.length > 1) mathNum += $parseInt(parts[1], R) / pow(R, parts[1].length);
|
||
|
if (R === 10 && numberToString(mathNum, R) !== string) throw new $SyntaxError(INVALID_NUMBER_REPRESENTATION);
|
||
|
return sign * mathNum;
|
||
|
}
|
||
|
});
|