Skip to content

Commit 49605b9

Browse files
authored
Split: Add support for longer strings (#1042)
1 parent bf5ce3c commit 49605b9

2 files changed

Lines changed: 19 additions & 4 deletions

File tree

source/split.d.ts

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -22,8 +22,14 @@ array = split(items, ',');
2222
export type Split<
2323
S extends string,
2424
Delimiter extends string,
25+
> = SplitHelper<S, Delimiter>;
26+
27+
type SplitHelper<
28+
S extends string,
29+
Delimiter extends string,
30+
Accumulator extends string[] = [],
2531
> = S extends `${infer Head}${Delimiter}${infer Tail}`
26-
? [Head, ...Split<Tail, Delimiter>]
27-
: S extends Delimiter
28-
? []
29-
: [S];
32+
? SplitHelper<Tail, Delimiter, [...Accumulator, Head]>
33+
: Delimiter extends ''
34+
? Accumulator
35+
: [...Accumulator, S];

test-d/split.ts

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import {expectType} from 'tsd';
22
import type {Split} from '../index';
3+
import type {BuildTuple} from '../source/internal';
34

45
declare function split<
56
S extends string,
@@ -28,3 +29,11 @@ expectType<[]>(split('', ''));
2829

2930
// Split empty string by any string.
3031
expectType<['']>(split('', ' '));
32+
33+
// Recursion depth at which a non-tail recursive implementation starts to fail.
34+
const fiftyZeroes = '00000000000000000000000000000000000000000000000000';
35+
expectType<BuildTuple<50, '0'>>(split(fiftyZeroes, ''));
36+
37+
// Maximum allowed recursion depth for a tail recursive implementation.
38+
const nineHundredNinetyNineZeroes = '000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000';
39+
expectType<BuildTuple<999, '0'>>(split(nineHundredNinetyNineZeroes, ''));

0 commit comments

Comments
 (0)