Created
June 25, 2025 14:58
-
-
Save dinocarl/ac407d2b9ed88e3ab3e721356063124b to your computer and use it in GitHub Desktop.
Recursive cond fn in typescript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
type Predicate<T> = (val: T) => boolean; | |
type Mapper<T, R> = (val: T) => R; | |
type CondTuple<T, R> = [Predicate<T>, Mapper<T, R>]; | |
function cond<T, R>(clauses: CondTuple<T, R>[] = []) { | |
const [[pred, mapr] = [undefined, undefined], ...rest] = clauses; | |
return (val: T): R | undefined => { | |
// base case: pred is undefined - exit the recursion | |
if (pred === undefined || mapr === undefined) { | |
return undefined; | |
} | |
// When applying the pred fn to val returns true, exit the recursion | |
// by returning the application of the mapr fn to val. otherwise recurse | |
return pred(val) ? mapr(val) : cond(rest)(val); | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment