Last active
March 12, 2021 19:41
-
-
Save wayneseymour/43f49a1cdc8d4d76e2be6b9ccbc5bad3 to your computer and use it in GitHub Desktop.
Task monad with some examples at the bottom
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
import { pipe } from './utils'; | |
export const Task = (fork) => ({ | |
fork, | |
map: (f) => Task((rej, res) => fork(rej, pipe(f, res))), | |
chain: (f) => Task((rej, res) => fork(rej, (x) => f(x).fork(rej, res))), | |
fold: (f, g) => | |
Task((rej, res) => | |
fork( | |
(x) => f(x).fork(rej, res), | |
(x) => g(x).fork(rej, res) | |
) | |
), | |
}); | |
Task.of = (x) => (rej, res) => res(x); | |
Task.fromPromised = (fn) => (...args) => | |
Task((rej, res) => | |
fn(...args) | |
.then(res) | |
.catch(rej) | |
); | |
}; | |
Task.rejected = (x) => Task((rej, res) => rej(x)); | |
const lifted = Task.of('pure') | |
lifted(x => console.error(`\n### x: \n\t${x}`), x => console.log(`\n### x: \n\t${x}`)) | |
const rejected = Task.rejected(2) | |
rejected.fork(x => console.error(`\n### x: \n\t${x}`), x => console.log(`\n### x: \n\t${x}`)) | |
const setTimeoutTask = Task((rej, res) => { | |
setTimeout(() => { | |
// res('resolved set timeout task'); | |
rej('rejected set timeout task'); | |
}, 300); | |
}) | |
setTimeoutTask.fork(x => console.error(`\n### x: \n\t${x}`), x => console.log(`\n### x: \n\t${x}`)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks to @DrBoolean for all his contributions to the fp in js world.