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