Skip to content

Instantly share code, notes, and snippets.

@unscriptable
Last active August 29, 2015 14:20
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 unscriptable/a840422f0dd2ec166474 to your computer and use it in GitHub Desktop.
Save unscriptable/a840422f0dd2ec166474 to your computer and use it in GitHub Desktop.
Maybe monad in javascript
export class Maybe {
constructor (f) {
this._run = f;
}
/**
* Transform the result of a maybe operation.
*/
map (f) {
return new this.constructor(t => {
return Promise.resolve(this._run(t)).then(f).fail(undef)
});
}
/**
* Extend the current maybe operation by merging it in sequence
* with another maybe operation returned by f.
*/
chain (f) {
return new this.constructor(t => {
return Promise.resolve(this._run(t))
.then(x => f(x)._run(t))
.fail(undef);
});
}
run (t) {
// what to do if this operation fails????
return this._run(t);
}
}
function undef () {}
@unscriptable
Copy link
Author

For fun, I decide to try to create a Maybe Monad in the spirit of Promises+iterators.

let foo = yield Maybe(funcThatMightFail).run(input);

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