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
Fsubstring in theSstring. We use the${}template literal syntax to split theSstring into 3 parts:Head: the part before the first occurrence ofF.F: the part that represents theFsubstring.Tail: the part after the first occurrence ofF.
- If
Fis found, we replace it withT, and recursively callReplaceAllon theTailstring until we've replaced all occurrences ofFinS. - If
Fis not found, we return the originalSstring.
The final output is a string with all occurrences of F replaced with T.