Skip to content

Instantly share code, notes, and snippets.

@jrsinclair
Created December 5, 2018 06:43
Show Gist options
  • Save jrsinclair/133d1eaf087cb15c87281f4dc6bb2646 to your computer and use it in GitHub Desktop.
Save jrsinclair/133d1eaf087cb15c87281f4dc6bb2646 to your computer and use it in GitHub Desktop.
Elegant Error Handling Code Samples
/**
*Left represents the sad path.
*/
class Left {
constructor(val) {
this._value = val;
}
map() {
// Left is the sad path
// so we do nothing
return this;
}
join() {
// On the sad path, we don't
// do anything with join
return this;
}
chain() {
// Boring sad path,
// do nothing.
return this;
}
toString() {
const str = this._value.toString();
return `Left(${$str})`;
}
}
/**
* Right represents the happy path
*/
class Right {
constructor(val) {
this._value = val;
}
map(fn) {
return new Right(
fn(this._value)
);
}
join() {
if ((this._value instanceof Left)
|| (this._value instanceof Right)) {
return this._value;
}
return this;
}
chain(fn) {
return fn(this._value);
}
toString() {
const str = this._value.toString();
return `Right(${str})`;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment