Skip to content

Commit

Permalink
Merge pull request #12 from tim-s-ccs/add-undefined-to-cast
Browse files Browse the repository at this point in the history
Update some of the rules of casting
  • Loading branch information
tim-s-ccs committed Feb 7, 2022
2 parents 13e459c + a902995 commit a537765
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 4 deletions.
8 changes: 6 additions & 2 deletions src/utils/cast.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,12 @@
const cast = (input: string, targetType: NumberConstructor|StringConstructor|BooleanConstructor): any => {
const cast = (input: string|undefined, targetType: NumberConstructor|StringConstructor|BooleanConstructor): string|number|boolean|undefined => {
if (input === undefined) return undefined

switch(targetType) {
case Number:
if (input.length > 0) {
return Number(input)
const number = Number(input)

return isNaN(number) ? undefined : number
} else {
return undefined
}
Expand Down
22 changes: 20 additions & 2 deletions test/utils/cast.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,22 @@ import { expect } from 'chai'

describe('cast', () => {
describe('when casting to \'Number\'', () => {
it('returns \'undefined\' when the input is undefined', () => {
const result = cast(undefined, Number)

expect(result).to.eq(undefined)
})

it('returns \'undefined\' when the input is \'\'', () => {
const result = cast('', Number)

expect(result).to.eq(undefined)
})

it('returns \'NaN\' when the input is a random string', () => {
it('returns \'undefined\' when the input is a random string', () => {
const result = cast('something', Number)

expect(result).to.be.NaN
expect(result).to.eq(undefined)
})

it('returns an integer when the input is an integer as a string', () => {
Expand All @@ -32,6 +38,12 @@ describe('cast', () => {
})

describe('when casting to \'String\'', () => {
it('returns \'undefined\' when the input is undefined', () => {
const result = cast(undefined, String)

expect(result).to.eq(undefined)
})

it('returns an empty string when the input is is \'\'', () => {
const result = cast('', String)

Expand All @@ -54,6 +66,12 @@ describe('cast', () => {
})

describe('when casting to \'Boolean\'', () => {
it('returns \'undefined\' when the input is undefined', () => {
const result = cast(undefined, Boolean)

expect(result).to.eq(undefined)
})

it('returns true when the input is is \'true\'', () => {
const result = cast('true', Boolean)

Expand Down

0 comments on commit a537765

Please sign in to comment.