Skip to content

Commit

Permalink
fix: fix string2Date function and add some tests
Browse files Browse the repository at this point in the history
  • Loading branch information
harryle95 committed May 8, 2024
1 parent 285d407 commit 9594466
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 4 deletions.
25 changes: 24 additions & 1 deletion src/components/helpers.test.ts
Original file line number Diff line number Diff line change
@@ -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"],
Expand All @@ -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);
}
});
});
12 changes: 9 additions & 3 deletions src/components/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 };

0 comments on commit 9594466

Please sign in to comment.