@newdash/newdash
Version:
javascript/typescript utility library
76 lines (75 loc) • 1.91 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.toNumber = void 0;
const isObject_1 = __importDefault(require("./isObject"));
const isSymbol_1 = __importDefault(require("./isSymbol"));
/**
* Used to detect bad signed hexadecimal string values.
* @ignore
*/
const reIsBadHex = /^[-+]0x[0-9a-f]+$/i;
/**
* Used to detect binary string values.
*
* @ignore
*/
const reIsBinary = /^0b[01]+$/i;
/**
* Used to detect octal string values.
* @ignore
*/
const reIsOctal = /^0o[0-7]+$/i;
/**
* Built-in method references without a dependency on `root`.
* @ignore
*/
const freeParseInt = parseInt;
/**
* Converts `value` to a number.
*
* @since 5.0.0
* @category Lang
* @param value The value to process.
* @returns Returns the number.
* @see [[isInteger]],[[toInteger]],[[isNumber]]
* @example
*
* ```js
* toNumber(3.2)
* // => 3.2
*
* toNumber(Number.MIN_VALUE)
* // => 5e-324
*
* toNumber(Infinity)
* // => Infinity
*
* toNumber('3.2')
* // => 3.2
* ```
*/
function toNumber(value) {
if (typeof value == "number") {
return value;
}
if ((0, isSymbol_1.default)(value)) {
return Number.NaN;
}
if ((0, isObject_1.default)(value)) {
const other = typeof value.valueOf == "function" ? value.valueOf() : value;
value = (0, isObject_1.default)(other) ? (`${other}`) : other;
}
if (typeof value != "string") {
return value === 0 ? value : +value;
}
value = value.trim();
const isBinary = reIsBinary.test(value);
return (isBinary || reIsOctal.test(value))
? freeParseInt(value.slice(2), isBinary ? 2 : 8)
: (reIsBadHex.test(value) ? Number.NaN : +value);
}
exports.toNumber = toNumber;
exports.default = toNumber;