Skip to content

Instantly share code, notes, and snippets.

@KEIII
Last active January 16, 2021 19:37
Show Gist options
  • Save KEIII/ced752286859282b0173c555b09de5fd to your computer and use it in GitHub Desktop.
Save KEIII/ced752286859282b0173c555b09de5fd to your computer and use it in GitHub Desktop.
Composite functions for TypeScript
type F<A, B> = (x: A) => B;
const chain = <A, B>(fab: F<A, B>) => {
return {
chain: <C>(fbc: F<B, C>) => chain((x: A) => fbc(fab(x))),
value: fab,
};
};
// example
const fromString = (s: string) => Number(s) || null;
const plus1 = (n: number) => n + 1;
const double = (n: number) => n * 2;
const print = (n: unknown) => `value is: ${n}`;
const notNull = <I, O>(f: F<I, O>) => (x: I | null) => {
return x === null ? null : f(x);
};
const math = chain(plus1).chain(double).value;
export const f = chain(fromString)
.chain(notNull(math))
.chain(notNull(plus1))
.chain(print)
.value;
console.log(f('42'));
console.log(f('wow'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment