Skip to content

Instantly share code, notes, and snippets.

@dinocarl
Created June 25, 2025 14:58
Show Gist options
  • Save dinocarl/ac407d2b9ed88e3ab3e721356063124b to your computer and use it in GitHub Desktop.
Save dinocarl/ac407d2b9ed88e3ab3e721356063124b to your computer and use it in GitHub Desktop.
Recursive cond fn in typescript
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