This solution is generated by ChatGPT, correctness is not guaranteed. You might also be able to find a solution fromcommunity posts.
AI solution for TypeScript puzzle on BFE.dev
44. implement ReplaceAll<S, F, T>
Here's one possible solution:
type ReplaceAll<S extends string, F extends string, T extends string> = S extends `${infer Head}${F}${infer Tail}` ? `${Head}${T}${ReplaceAll<Tail, F, T>}` : S;
Explanation:
The ReplaceAll
type takes in 3 type parameters:
S
: the string to search and replace in.F
: the substring to search for.T
: the replacement string.
We implement it recursively using conditional types. Here's how it works:
- We first check if there's an occurrence of the
F
substring in theS
string. We use the${}
template literal syntax to split theS
string into 3 parts:Head
: the part before the first occurrence ofF
.F
: the part that represents theF
substring.Tail
: the part after the first occurrence ofF
.
- If
F
is found, we replace it withT
, and recursively callReplaceAll
on theTail
string until we've replaced all occurrences ofF
inS
. - If
F
is not found, we return the originalS
string.
The final output is a string with all occurrences of F
replaced with T
.