Skip to content

Instantly share code, notes, and snippets.

@snewell92
Created December 18, 2017 20:46
Show Gist options
  • Save snewell92/9e684f29f7096914e8624ff4dc1b9b41 to your computer and use it in GitHub Desktop.
Save snewell92/9e684f29f7096914e8624ff4dc1b9b41 to your computer and use it in GitHub Desktop.
Typescript ifThen pattern
import { curry } from 'lodash';
export type Predicate = () => boolean;
export type Func<a> = () => a;
export interface ThenElse<T = void, E = T> {
t: Func<T>,
e: Func<E>
}
export const makeThenElse = <T = void, E = T>(t: Func<T>, e: Func<E>): ThenElse<T, E> => ({ t, e });
// Some type predicates
export const isFunc = (a: Function | any): a is Function => typeof a === 'function';
export const isBool = (c: boolean | Predicate | any): c is boolean => typeof c === 'boolean';
export const isNum = (n?: number): n is number => !!n;
const _ifThen = <T, E = T>(cond: boolean, o: ThenElse<T>): T => cond ? o.t() : o.e();
export const ifThen = curry((cond: boolean | Predicate, o: ThenElse): void =>
isBool(cond)
? _ifThen(cond, o)
: _ifThen(cond(), o));
export const ifNumThen = (n: number | undefined, t: Func<number>): void =>
ifThen(isNum(n), makeThenElse(t, () => null));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment