blob: e776bb2b7ec249562c7c52c97ab6cc8c6be6a7c4 [file] [log] [blame]
Leo Repp58b9f112021-11-22 11:57:47 +01001'use strict';
2
3var GetIntrinsic = require('get-intrinsic');
4
5var $TypeError = GetIntrinsic('%TypeError%');
6var $Number = GetIntrinsic('%Number%');
7var $RegExp = GetIntrinsic('%RegExp%');
8var $parseInteger = GetIntrinsic('%parseInt%');
9
10var callBound = require('call-bind/callBound');
11var regexTester = require('../helpers/regexTester');
12var isPrimitive = require('../helpers/isPrimitive');
13
14var $strSlice = callBound('String.prototype.slice');
15var isBinary = regexTester(/^0b[01]+$/i);
16var isOctal = regexTester(/^0o[0-7]+$/i);
17var isInvalidHexLiteral = regexTester(/^[-+]0x[0-9a-f]+$/i);
18var nonWS = ['\u0085', '\u200b', '\ufffe'].join('');
19var nonWSregex = new $RegExp('[' + nonWS + ']', 'g');
20var hasNonWS = regexTester(nonWSregex);
21
22// whitespace from: https://es5.github.io/#x15.5.4.20
23// implementation from https://github.com/es-shims/es5-shim/blob/v3.4.0/es5-shim.js#L1304-L1324
24var ws = [
25 '\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003',
26 '\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028',
27 '\u2029\uFEFF'
28].join('');
29var trimRegex = new RegExp('(^[' + ws + ']+)|([' + ws + ']+$)', 'g');
30var $replace = callBound('String.prototype.replace');
31var $trim = function (value) {
32 return $replace(value, trimRegex, '');
33};
34
35var ToPrimitive = require('./ToPrimitive');
36
37// https://ecma-international.org/ecma-262/6.0/#sec-tonumber
38
39module.exports = function ToNumber(argument) {
40 var value = isPrimitive(argument) ? argument : ToPrimitive(argument, $Number);
41 if (typeof value === 'symbol') {
42 throw new $TypeError('Cannot convert a Symbol value to a number');
43 }
44 if (typeof value === 'string') {
45 if (isBinary(value)) {
46 return ToNumber($parseInteger($strSlice(value, 2), 2));
47 } else if (isOctal(value)) {
48 return ToNumber($parseInteger($strSlice(value, 2), 8));
49 } else if (hasNonWS(value) || isInvalidHexLiteral(value)) {
50 return NaN;
51 } else {
52 var trimmed = $trim(value);
53 if (trimmed !== value) {
54 return ToNumber(trimmed);
55 }
56 }
57 }
58 return $Number(value);
59};