Skip to content

Commit

Permalink
fix: narrow types for SplitByCase
Browse files Browse the repository at this point in the history
  • Loading branch information
ntnyq committed Nov 20, 2024
1 parent 7d7883d commit 80248aa
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 12 deletions.
23 changes: 11 additions & 12 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,21 +21,18 @@ type CapitalizedWords<
Accumulator extends string = "",
> = T extends readonly []
? Accumulator
: T extends readonly [infer F extends string]
: T extends readonly [infer F extends string, ...infer R extends string[]]
? CapitalizedWords<
[],
R,
Joiner,
Normalize,
`${Accumulator}${Capitalize<Normalize extends true ? Lowercase<F> : F>}`
`${Accumulator}${Capitalize<Normalize extends true ? Lowercase<F> : F>}${[
LastOfArray<R>,
] extends [never]
? ""
: Joiner}`
>
: T extends readonly [infer F extends string, ...infer R extends string[]]
? CapitalizedWords<
R,
Joiner,
Normalize,
`${Accumulator}${Capitalize<Normalize extends true ? Lowercase<F> : F>}${Joiner}`
>
: Accumulator;
: Accumulator;

type JoinLowercaseWords<
T extends readonly string[],
Expand Down Expand Up @@ -99,7 +96,9 @@ export type SplitByCase<
? string[]
: T extends `${infer F}${infer R}`
? [LastOfArray<Accumulator>] extends [never]
? SplitByCase<R, Separator, [F]>
? F extends Separator | Whitespace
? SplitByCase<R, Separator, []>
: SplitByCase<R, Separator, [F]>
: LastOfArray<Accumulator> extends string
? R extends ""
? SplitByCase<
Expand Down
2 changes: 2 additions & 0 deletions test/scule.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@ describe("splitByCase", () => {
["foo123-bar", ["foo123", "bar"]],
["FOOBar", ["FOO", "Bar"]],
["ALink", ["A", "Link"]],
["-FooBar", ["", "Foo", "Bar"]],
[" FooBar", ["", "Foo", "Bar"]],
// with custom splitters
[
"foo\\Bar.fuzz-FIZz",
Expand Down
2 changes: 2 additions & 0 deletions test/types.test-d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ describe("SplitByCase", () => {
assertType<SplitByCase<"ALink">>(["A", "Link"]);
assertType<SplitByCase<"FOO_BAR">>(["FOO", "BAR"]);
assertType<SplitByCase<"Foo Bar Baz">>(["Foo", "Bar", "Baz"]);
assertType<SplitByCase<"-Bar Baz">>(["Bar", "Baz"]);
assertType<SplitByCase<" Bar Baz">>(["Bar", "Baz"]);
});

test("custom splitters", () => {
Expand Down

0 comments on commit 80248aa

Please sign in to comment.