1 | 'use strict';
|
---|
2 |
|
---|
3 | var GetIntrinsic = require('get-intrinsic');
|
---|
4 |
|
---|
5 | var $TypeError = require('es-errors/type');
|
---|
6 | var $Number = GetIntrinsic('%Number%');
|
---|
7 | var $RegExp = GetIntrinsic('%RegExp%');
|
---|
8 | var $parseInteger = GetIntrinsic('%parseInt%');
|
---|
9 |
|
---|
10 | var callBound = require('call-bind/callBound');
|
---|
11 | var regexTester = require('safe-regex-test');
|
---|
12 | var isPrimitive = require('../helpers/isPrimitive');
|
---|
13 |
|
---|
14 | var $strSlice = callBound('String.prototype.slice');
|
---|
15 | var isBinary = regexTester(/^0b[01]+$/i);
|
---|
16 | var isOctal = regexTester(/^0o[0-7]+$/i);
|
---|
17 | var isInvalidHexLiteral = regexTester(/^[-+]0x[0-9a-f]+$/i);
|
---|
18 | var nonWS = ['\u0085', '\u200b', '\ufffe'].join('');
|
---|
19 | var nonWSregex = new $RegExp('[' + nonWS + ']', 'g');
|
---|
20 | var hasNonWS = regexTester(nonWSregex);
|
---|
21 |
|
---|
22 | var $trim = require('string.prototype.trim');
|
---|
23 |
|
---|
24 | var ToPrimitive = require('./ToPrimitive');
|
---|
25 |
|
---|
26 | // https://262.ecma-international.org/6.0/#sec-tonumber
|
---|
27 |
|
---|
28 | module.exports = function ToNumber(argument) {
|
---|
29 | var value = isPrimitive(argument) ? argument : ToPrimitive(argument, $Number);
|
---|
30 | if (typeof value === 'symbol') {
|
---|
31 | throw new $TypeError('Cannot convert a Symbol value to a number');
|
---|
32 | }
|
---|
33 | if (typeof value === 'bigint') {
|
---|
34 | throw new $TypeError('Conversion from \'BigInt\' to \'number\' is not allowed.');
|
---|
35 | }
|
---|
36 | if (typeof value === 'string') {
|
---|
37 | if (isBinary(value)) {
|
---|
38 | return ToNumber($parseInteger($strSlice(value, 2), 2));
|
---|
39 | } else if (isOctal(value)) {
|
---|
40 | return ToNumber($parseInteger($strSlice(value, 2), 8));
|
---|
41 | } else if (hasNonWS(value) || isInvalidHexLiteral(value)) {
|
---|
42 | return NaN;
|
---|
43 | }
|
---|
44 | var trimmed = $trim(value);
|
---|
45 | if (trimmed !== value) {
|
---|
46 | return ToNumber(trimmed);
|
---|
47 | }
|
---|
48 |
|
---|
49 | }
|
---|
50 | return $Number(value);
|
---|
51 | };
|
---|