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