Как насчет этого?
class Either {}
class Left extends Either {
constructor(leftValue) {
super()
this.leftValue = leftValue;
}
match(lHandler, unused) {
return lHandler(this.leftValue);
}
}
class Right extends Either {
constructor(rightValue) {
super()
this.rightValue = rightValue;
}
match(unused, rHandler) {
return rHandler(this.rightValue);
}
}
Использование:
const either = ... // e.g. new Left('Test');
either.match(
left => console.log(left),
right => console.warn('An error occurred'),
);
Чтобы сделать это действительно полезным, я предлагаю добавить map
, flatMap
и т. Д.