Created
January 3, 2017 23:25
-
-
Save jrsinclair/a3ed0b6b03be8bc96e5c7cecdc1e83e1 to your computer and use it in GitHub Desktop.
Lightweight Either Implementation. Mostly ripped off directly from @DrBoolean's Mostly Adequate Guide.
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
/** | |
* Lightweight Either Implementation. | |
* Mostly ripped off directly from @drboolean's Mostly Adequate Guide. | |
* https://drboolean.gitbooks.io/mostly-adequate-guide/ | |
*/ | |
import {curry} from 'lodash/fp'; | |
export function Left(x) { | |
this.__value = x; | |
} | |
Left.of = function of(x) { | |
return new Left(x); | |
}; | |
Left.prototype.map = function map() { | |
return this; | |
}; | |
Left.prototype.join = function join() { | |
return this; | |
}; | |
Left.prototype.chain = function chain(fn) { | |
return this.map(fn).join(); | |
}; | |
export function Right(x) { | |
this.__value = x; | |
} | |
Right.of = function of(x) { | |
return new Right(x); | |
}; | |
Right.prototype.map = function map(f) { | |
return Right.of(f(this.__value)); | |
}; | |
Right.prototype.join = function join() { | |
return this.__value; | |
}; | |
Right.prototype.chain = function chain(fn) { | |
return this.map(fn).join(); | |
}; | |
/** | |
* @function Either. Do something with an either value. | |
* @param {function} f Function to run if the value is Left | |
* @param {function} g Function to run if the value is Right. | |
* @param {Either} e An Either monad containing either a Left or Right | |
* @return {*} The result of calling f or g on the corresponding Either value. | |
*/ | |
export const either = curry(function either(f, g, e) { // eslint-disable-line prefer-arrow-callback | |
switch (e.constructor) { | |
case Left: | |
return f(e.__value); | |
case Right: | |
return g(e.__value); | |
default: | |
throw new Error('Something weird passed to either'); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment