Skip to content

Instantly share code, notes, and snippets.

@danieldram
Last active April 4, 2017 06:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danieldram/5132c6d82df6748970fc1b9c192e0437 to your computer and use it in GitHub Desktop.
Save danieldram/5132c6d82df6748970fc1b9c192e0437 to your computer and use it in GitHub Desktop.
Either Functional Error Handling Strategy
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