Skip to content

Commit

Permalink
Split: Add support for longer strings (#1042)
Browse files Browse the repository at this point in the history
  • Loading branch information
som-sm authored Jan 16, 2025
1 parent bf5ce3c commit 49605b9
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 4 deletions.
14 changes: 10 additions & 4 deletions source/split.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,14 @@ array = split(items, ',');
export type Split<
S extends string,
Delimiter extends string,
> = SplitHelper<S, Delimiter>;

type SplitHelper<
S extends string,
Delimiter extends string,
Accumulator extends string[] = [],
> = S extends `${infer Head}${Delimiter}${infer Tail}`
? [Head, ...Split<Tail, Delimiter>]
: S extends Delimiter
? []
: [S];
? SplitHelper<Tail, Delimiter, [...Accumulator, Head]>
: Delimiter extends ''
? Accumulator
: [...Accumulator, S];
9 changes: 9 additions & 0 deletions test-d/split.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import {expectType} from 'tsd';
import type {Split} from '../index';
import type {BuildTuple} from '../source/internal';

declare function split<
S extends string,
Expand Down Expand Up @@ -28,3 +29,11 @@ expectType<[]>(split('', ''));

// Split empty string by any string.
expectType<['']>(split('', ' '));

// Recursion depth at which a non-tail recursive implementation starts to fail.
const fiftyZeroes = '00000000000000000000000000000000000000000000000000';
expectType<BuildTuple<50, '0'>>(split(fiftyZeroes, ''));

// Maximum allowed recursion depth for a tail recursive implementation.
const nineHundredNinetyNineZeroes = '000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000';
expectType<BuildTuple<999, '0'>>(split(nineHundredNinetyNineZeroes, ''));

0 comments on commit 49605b9

Please sign in to comment.