Skip to content

Commit

Permalink
allow null default in toFloat and toInt (#134)
Browse files Browse the repository at this point in the history
  • Loading branch information
sodiray authored Nov 2, 2022
1 parent 60de1e3 commit 370cc44
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 7 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "radash",
"version": "9.0.0",
"version": "9.0.1",
"description": "Functional utility library - modern, simple, typed, powerful",
"main": "dist/cjs/index.cjs",
"module": "dist/esm/index.mjs",
Expand Down
20 changes: 14 additions & 6 deletions src/number.ts
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
}
8 changes: 8 additions & 0 deletions src/tests/number.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,10 @@ describe('number module', () => {
const result = _.toFloat(undefined)
assert.strictEqual(result, 0.0)
})
test('uses null default', () => {
const result = _.toFloat('x', null)
assert.strictEqual(result, null)
})
test('handles bad input', () => {
const result = _.toFloat({})
assert.strictEqual(result, 0.0)
Expand All @@ -25,6 +29,10 @@ describe('number module', () => {
const result = _.toInt(null)
assert.strictEqual(result, 0)
})
test('uses null default', () => {
const result = _.toInt('x', null)
assert.strictEqual(result, null)
})
test('handles undefined', () => {
const result = _.toInt(undefined)
assert.strictEqual(result, 0)
Expand Down

0 comments on commit 370cc44

Please sign in to comment.