mezzanine
Version:
Fantasy land union types with pattern matching
112 lines (98 loc) • 2.1 kB
JavaScript
'use strict';Object.defineProperty(exports, "__esModule", { value: true });var
Either = exports.Either = class Either {
case(select) {
switch (this.status) {
case 'right':{
var data = this.value;
return select.Right(data);
}
case 'left':{
var _data = this.value;
return select.Left(_data);
}
default:{
throw new TypeError(`[Either] Unexpected status ${this.status}`);
}}
}
caseWrap(select) {
var result = this.case(select);
//$FlowIssue
var wrapped = new Either(result, this.status);
return wrapped;
}
isRight() {
return this.case({
Right: () => true,
Left: () => false });
}
isLeft() {
return this.case({
Right: () => false,
Left: () => true });
}
map(fn) {
return this.case({
Right: fn,
Left: val => val });
}
mapl(fn) {
return this.caseWrap({
Right: val => val,
Left: fn });
}
bimap(fnRight, fnLeft) {
return this.caseWrap({
Right: fnRight,
Left: fnLeft });
}
chain(fn) {
//$FlowIssue
return this.case({
Right: fn,
Left: () => this });
}
chainl(fn) {
//$FlowIssue
return this.case({
Right: () => this,
Left: fn });
}
//$FlowIssue
alt(either) {
if (this.isRight()) return this;
return either.isRight() ?
either :
this;
}
static Right(val) {
var result = new Either(val, 'right');
return result;
}
static Left(val) {
var result = new Either(val, 'left');
return result;
}
static of(val) {
var result = new Either(val, 'right');
return result;
}
static when(fn, val) {
var status = fn(val) ?
'right' :
'left';
return new Either(val, status);
}
//$FlowIssue
static validate(fn,
select,
val) {
//$FlowIssue
var raw = Either.when(fn, val);
return raw.caseWrap(select);
}
constructor(value, status) {
this.value = value;
this.status = status;
}};exports.default =
Either;
//# sourceMappingURL=either.js.map