1 |
3a515b92
|
cagy
|
'use strict';
|
2 |
|
|
|
3 |
|
|
var GetIntrinsic = require('../GetIntrinsic');
|
4 |
|
|
|
5 |
|
|
var $TypeError = GetIntrinsic('%TypeError%');
|
6 |
|
|
var $Number = GetIntrinsic('%Number%');
|
7 |
|
|
var $RegExp = GetIntrinsic('%RegExp%');
|
8 |
|
|
var $parseInteger = GetIntrinsic('%parseInt%');
|
9 |
|
|
|
10 |
|
|
var callBound = require('../helpers/callBound');
|
11 |
|
|
var regexTester = require('../helpers/regexTester');
|
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 |
|
|
// 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
|
24 |
|
|
var 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('');
|
29 |
|
|
var trimRegex = new RegExp('(^[' + ws + ']+)|([' + ws + ']+$)', 'g');
|
30 |
|
|
var $replace = callBound('String.prototype.replace');
|
31 |
|
|
var $trim = function (value) {
|
32 |
|
|
return $replace(value, trimRegex, '');
|
33 |
|
|
};
|
34 |
|
|
|
35 |
|
|
var ToPrimitive = require('./ToPrimitive');
|
36 |
|
|
|
37 |
|
|
// https://www.ecma-international.org/ecma-262/6.0/#sec-tonumber
|
38 |
|
|
|
39 |
|
|
module.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 |
|
|
};
|