-
Notifications
You must be signed in to change notification settings - Fork 173
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
allow null default in toFloat and toInt (#134)
- Loading branch information
Showing
3 changed files
with
23 additions
and
7 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,15 +1,23 @@ | ||
export const toFloat = (value: any, defaultValue: number = 0.0) => { | ||
export const toFloat = <T extends number | null = number>( | ||
value: any, | ||
defaultValue?: T | ||
): number | T => { | ||
const def = defaultValue === undefined ? 0.0 : defaultValue | ||
if (value === null || value === undefined) { | ||
return defaultValue | ||
return def | ||
} | ||
const result = parseFloat(value) | ||
return isNaN(result) ? defaultValue : result | ||
return isNaN(result) ? def : result | ||
} | ||
|
||
export const toInt = (value: any, defaultValue: number = 0) => { | ||
export const toInt = <T extends number | null>( | ||
value: any, | ||
defaultValue?: T | ||
): number | T => { | ||
const def = defaultValue === undefined ? 0 : defaultValue | ||
if (value === null || value === undefined) { | ||
return defaultValue | ||
return def | ||
} | ||
const result = parseInt(value) | ||
return isNaN(result) ? defaultValue : result | ||
return isNaN(result) ? def : result | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters