Skip to content

Instantly share code, notes, and snippets.

@wayneseymour
Last active March 12, 2021 19:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wayneseymour/43f49a1cdc8d4d76e2be6b9ccbc5bad3 to your computer and use it in GitHub Desktop.
Save wayneseymour/43f49a1cdc8d4d76e2be6b9ccbc5bad3 to your computer and use it in GitHub Desktop.
Task monad with some examples at the bottom
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}`))
@wayneseymour
Copy link
Author

Thanks to @DrBoolean for all his contributions to the fp in js world.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment