From 9594466c5348969176ac29e362f9ceedf0ef3f3c Mon Sep 17 00:00:00 2001 From: harryle Date: Wed, 8 May 2024 19:08:42 +0930 Subject: [PATCH] fix: fix string2Date function and add some tests --- src/components/helpers.test.ts | 25 ++++++++++++++++++++++++- src/components/helpers.ts | 12 +++++++++--- 2 files changed, 33 insertions(+), 4 deletions(-) diff --git a/src/components/helpers.test.ts b/src/components/helpers.test.ts index c819ee9..8fa866c 100644 --- a/src/components/helpers.test.ts +++ b/src/components/helpers.test.ts @@ -1,7 +1,12 @@ -import { capitalise, toSnakeCase } from "./helpers"; +import { capitalise, string2Date, toSnakeCase } from "./helpers"; import { describe, expect, test } from "vitest"; const capitaliseFixture = [ + ["", ""], + ["a", "A"], + [" ", ""], + ["A ", "A"], + ["first name ", "FirstName"], ["firstName", "FirstName"], ["lastName", "LastName"], ["first name", "FirstName"], @@ -24,3 +29,21 @@ describe.each(snakeCaseFixture)("given %s", (inputValue, expValue) => { expect(toSnakeCase(inputValue)).toBe(expValue); }); }); + +const string2DateFixture: Array<[string | null | undefined, Date | null]> = [ + ["", null], + ["a", null], + ["2011-02-04", new Date("2011-02-04")], + [null, null], + [undefined, null], +]; + +describe.each(string2DateFixture)("given %s", (inputValue, expValue) => { + test(`string2Date returns ${expValue}`, () => { + if (expValue === null) { + expect(string2Date(inputValue)).toBeNull(); + } else { + expect(string2Date(inputValue)).toEqual(expValue); + } + }); +}); diff --git a/src/components/helpers.ts b/src/components/helpers.ts index 2035e13..004cfc5 100644 --- a/src/components/helpers.ts +++ b/src/components/helpers.ts @@ -7,15 +7,21 @@ const capitalise = (text: string) => { if (processedText.length == 0) return ""; if (processedText.length == 1) return text[0]?.toUpperCase(); - processedText = toSnakeCase(text); + processedText = toSnakeCase(processedText); const snakeToCamel = (s: string) => s.replace(/(_\w)/g, (k) => k[1]!.toUpperCase()); processedText = snakeToCamel(processedText); return processedText[0]!.toUpperCase() + processedText.slice(1); }; -const string2Date = (text?: string) => { - return text ? new Date(text) : null; +const string2Date = (text?: string | null) => { + if (text) { + let parsedDate = new Date(text); + if (!isNaN(parsedDate.getDate())) { + return parsedDate; + } + } + return null; }; export { capitalise, toSnakeCase, string2Date };