Last active
August 29, 2015 14:20
-
-
Save unscriptable/a840422f0dd2ec166474 to your computer and use it in GitHub Desktop.
Maybe monad in javascript
This file contains 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
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 () {} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
For fun, I decide to try to create a Maybe Monad in the spirit of Promises+iterators.