Last active
January 16, 2021 19:37
-
-
Save KEIII/ced752286859282b0173c555b09de5fd to your computer and use it in GitHub Desktop.
Composite functions for 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 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