Created
December 5, 2018 06:43
-
-
Save jrsinclair/133d1eaf087cb15c87281f4dc6bb2646 to your computer and use it in GitHub Desktop.
Elegant Error Handling Code Samples
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
/** | |
*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})`; | |
} | |
} |
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
/** | |
* 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