Skip to content

Instantly share code, notes, and snippets.

@futantan
Last active March 27, 2019 10:05
Show Gist options
  • Select an option

  • Save futantan/b4cb6913e0a71e207e5c7517f626b394 to your computer and use it in GitHub Desktop.

Select an option

Save futantan/b4cb6913e0a71e207e5c7517f626b394 to your computer and use it in GitHub Desktop.
const compose = (f, g) => (...args) => f(g(...args));
class Task {
constructor(fork) { this.fork = fork; }
static of (fork) { return new Task(fork); }
map(f) { return Task.of((rej, res) => this.fork(rej, compose(res, f))); }
chain(f) { return Task.of((rej, res) => this.fork(rej, x => f(x).fork(rej, res))); }
ap(task) { return Task.of((rej, res) => this.fork(rej, f => task.fork(rej, compose(res, f)))); }
static fromPromise(f, ...args) {
return Task.of((reject, resolve) => f(...args).then(resolve, reject));
}
}
const getTimer = wait => Task.of((rej, res) => setTimeout(res, wait, `Wait for ${wait}`));
Task.of((rej, res) => res(x => y => ({x, y})))
.ap(getTimer(500).map(x => `First ${x}`))
.ap(getTimer(100).map(x => `Second ${x}`))
.fork(console.error, console.log);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment