Last active
April 4, 2017 06:36
-
-
Save danieldram/5132c6d82df6748970fc1b9c192e0437 to your computer and use it in GitHub Desktop.
Either Functional Error Handling Strategy
This file contains hidden or 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
const Right = x => | |
({ | |
map: f => Right(f(x)), | |
fold: (f,g) => g(x), | |
inspect: f => f(`Right(${x})`) | |
}) | |
const Left = x => | |
({ | |
map: f => Left(x), | |
fold:(f,g) => f(x), | |
inspect: f => f(`Left(${x})`) | |
}) | |
//This is where the actual error handling logic resides. | |
const fromNullable = (data) => data != null ? Right(data): Left(null) | |
//there shoudl only ever be one expression in a pure function, so return obj or null | |
const findColor = (name) => fromNullable({black:'#000', white:'#fff'}[name]) | |
//Failure Case - Notice that both functions have a failure case, but truthy executes right, falsey left. | |
let greyExists = findColor('grey').fold(e=>"error", data=>data) | |
console.log(greyExists) | |
//Successful Case | |
let blackExists= findColor('black').fold(e=>"error", data=>data) | |
console.log(blackExists) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment