50 lines
1.7 KiB
JavaScript
50 lines
1.7 KiB
JavaScript
// Converts any value to a number, like the spec's ToNumber
|
|
function Number(x) {
|
|
switch (typeof x) {
|
|
case "number": return x;
|
|
case "string": return __native_string_to_number(x);
|
|
case "boolean": return x ? 1 : 0;
|
|
case "undefined": return NaN;
|
|
case "object": return x === null ? 0 : NaN;
|
|
default: return NaN;
|
|
}
|
|
}
|
|
|
|
Number.NaN = NaN;
|
|
Number.POSITIVE_INFINITY = Infinity;
|
|
Number.NEGATIVE_INFINITY = -Infinity;
|
|
Number.MAX_SAFE_INTEGER = 9007199254740991;
|
|
Number.MIN_SAFE_INTEGER = -9007199254740991;
|
|
|
|
Number.isNaN = function (x) { return typeof x === "number" && x !== x; };
|
|
Number.isFinite = function (x) { return typeof x === "number" && x === x && x !== Infinity && x !== -Infinity; };
|
|
Number.isInteger = function (x) { return Number.isFinite(x) && x % 1 === 0; };
|
|
|
|
// In these methods `this` is the primitive number itself
|
|
Number.prototype = {
|
|
toString(radix) {
|
|
if (radix === undefined || radix === 10) return __native_number_to_string(this);
|
|
return integerToString(this, radix);
|
|
},
|
|
toFixed(digits) { return __native_number_to_fixed(this, digits === undefined ? 0 : digits); },
|
|
valueOf() { return this; },
|
|
};
|
|
|
|
__link_proto_number(Number.prototype);
|
|
|
|
// An integer in `radix` (2 to 36). Only integers: the fraction is dropped
|
|
function integerToString(n, radix) {
|
|
let negative = n < 0;
|
|
if (negative) n = -n;
|
|
n = n - (n % 1);
|
|
|
|
let out = "";
|
|
do {
|
|
let digit = n % radix;
|
|
out = __native_string_concat(__native_string_from_char_code(digit < 10 ? 48 + digit : 87 + digit), out);
|
|
n = (n - digit) / radix;
|
|
} while (n > 0);
|
|
|
|
return negative ? __native_string_concat("-", out) : out;
|
|
}
|