Skip to content

Commit

Permalink
feat: added options to tonumber method
Browse files Browse the repository at this point in the history
1) Added options as second param for toNumber
2) defaultValue will be returned in case if NaN occurs
3) Updated example and docs for toNumber
  • Loading branch information
kapilkumar-github committed Apr 23, 2024
1 parent 8c4ead4 commit ed52e0c
Showing 1 changed file with 30 additions and 9 deletions.
39 changes: 30 additions & 9 deletions src/toNumber.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@ const freeParseInt = parseInt;
* @since 4.0.0
* @category Lang
* @param {*} value The value to process.
* @param {Object} [options={}] The options object.
* @param {number} [options.defaultValue=0] If NaN occurs, the options.defaultValue argument will be returned.
* @returns {number} Returns the number.
* @see isInteger, toInteger, isNumber
* @example
Expand All @@ -40,8 +42,22 @@ const freeParseInt = parseInt;
*
* toNumber('3.2')
* // => 3.2
*
* toNumber("someStringValue")
* // => NaN
*
* toNumber("someStringValue", {})
* // => NaN
*
* toNumber("someStringValue", {defaultValue: 0})
* // => 0
*
* toNumber("23", {defaultValue: 0})
* // => 23
*/
function toNumber(value, defaultValue = NAN) {
function toNumber(value, options = { defaultValue: NAN }) {
const { defaultValue = NAN } = options;
let finalValue;
if (typeof value === 'number') {
return value;
}
Expand All @@ -53,15 +69,20 @@ function toNumber(value, defaultValue = NAN) {
value = isObject(other) ? `${other}` : other;
}
if (typeof value !== 'string') {
return value === 0 ? value : +value;
finalValue = value === 0 ? value : +value;
} else {
value = value.replace(reTrim, '');
const isBinary = reIsBinary.test(value);

finalValue =
isBinary || reIsOctal.test(value)
? freeParseInt(value.slice(2), isBinary ? 2 : 8)
: reIsBadHex.test(value)
? defaultValue
: +value;
}
value = value.replace(reTrim, '');
const isBinary = reIsBinary.test(value);
return isBinary || reIsOctal.test(value)
? freeParseInt(value.slice(2), isBinary ? 2 : 8)
: reIsBadHex.test(value)
? defaultValue
: +value;
if (Number.isNaN(finalValue)) return defaultValue;
return finalValue;
}

export default toNumber;

0 comments on commit ed52e0c

Please sign in to comment.