1 | 'use strict';
|
---|
2 |
|
---|
3 | var GetIntrinsic = require('get-intrinsic');
|
---|
4 |
|
---|
5 | var $RegExp = GetIntrinsic('%RegExp%');
|
---|
6 | var $TypeError = require('es-errors/type');
|
---|
7 | var $parseInteger = GetIntrinsic('%parseInt%');
|
---|
8 |
|
---|
9 | var callBound = require('call-bound');
|
---|
10 | var regexTester = require('safe-regex-test');
|
---|
11 |
|
---|
12 | var $strSlice = callBound('String.prototype.slice');
|
---|
13 | var isBinary = regexTester(/^0b[01]+$/i);
|
---|
14 | var isOctal = regexTester(/^0o[0-7]+$/i);
|
---|
15 | var isInvalidHexLiteral = regexTester(/^[-+]0x[0-9a-f]+$/i);
|
---|
16 | var nonWS = ['\u0085', '\u200b', '\ufffe'].join('');
|
---|
17 | var nonWSregex = new $RegExp('[' + nonWS + ']', 'g');
|
---|
18 | var hasNonWS = regexTester(nonWSregex);
|
---|
19 |
|
---|
20 | var $trim = require('string.prototype.trim');
|
---|
21 |
|
---|
22 | // https://262.ecma-international.org/13.0/#sec-stringtonumber
|
---|
23 |
|
---|
24 | module.exports = function StringToNumber(argument) {
|
---|
25 | if (typeof argument !== 'string') {
|
---|
26 | throw new $TypeError('Assertion failed: `argument` is not a String');
|
---|
27 | }
|
---|
28 | if (isBinary(argument)) {
|
---|
29 | return +$parseInteger($strSlice(argument, 2), 2);
|
---|
30 | }
|
---|
31 | if (isOctal(argument)) {
|
---|
32 | return +$parseInteger($strSlice(argument, 2), 8);
|
---|
33 | }
|
---|
34 | if (hasNonWS(argument) || isInvalidHexLiteral(argument)) {
|
---|
35 | return NaN;
|
---|
36 | }
|
---|
37 | var trimmed = $trim(argument);
|
---|
38 | if (trimmed !== argument) {
|
---|
39 | return StringToNumber(trimmed);
|
---|
40 | }
|
---|
41 | return +argument;
|
---|
42 | };
|
---|