From a90299578bdef705b4ae0e43600760d5fc0529fe Mon Sep 17 00:00:00 2001 From: tim-s-ccs Date: Mon, 7 Feb 2022 09:46:25 +0000 Subject: [PATCH] Update some of the rules of casting --- src/utils/cast.ts | 8 ++++++-- test/utils/cast.test.ts | 22 ++++++++++++++++++++-- 2 files changed, 26 insertions(+), 4 deletions(-) diff --git a/src/utils/cast.ts b/src/utils/cast.ts index 17198a7..01e99a8 100644 --- a/src/utils/cast.ts +++ b/src/utils/cast.ts @@ -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 } diff --git a/test/utils/cast.test.ts b/test/utils/cast.test.ts index 8fad408..3a3938f 100644 --- a/test/utils/cast.test.ts +++ b/test/utils/cast.test.ts @@ -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', () => { @@ -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) @@ -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)