Skip to content

Instantly share code, notes, and snippets.

@dinocarl
Created March 30, 2025 17:11
Show Gist options
  • Save dinocarl/e641b64dab048423273f276158807c53 to your computer and use it in GitHub Desktop.
Save dinocarl/e641b64dab048423273f276158807c53 to your computer and use it in GitHub Desktop.
type Predicate<T> = (value: T) => boolean;
type Mapper<T, R> = (value: T) => R;
type CondPair<T, R> = [Predicate<T>, Mapper<T, R>];
// recursive cond that can breaks early or returns undefined
const cond = <T, R>(
[[pred, mapr] = [] as unknown as CondPair<T, R>, ...rest]: CondPair<T, R>[] = []
): ((val: T) => R | undefined) => (val: T): R | undefined =>
!pred ? undefined :
pred(val) ? mapr(val) : cond(rest)(val);
const stateOfWaterAt = cond<number, string>([
[(n) => n >= 100, () => `gas`],
[(n) => n <= 0, () => `solid`],
[(n) => true, () => `liquid`]
]);
// nicer w ramda utility fns
const _stateOfWaterAt = cond<number, string>([
[lte(100), always('gas')],
[gte(0), always('solid')],
[T, always('liquid')]
]);
[
[ -10, 0, 10, 90, 100, 110 ].map(stateOfWaterAt),
[ -10, 0, 10, 90, 100, 110 ].map(_stateOfWaterAt),
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment