Skip to content

Instantly share code, notes, and snippets.

@jjhiggz
Created August 15, 2024 04:08
Show Gist options
  • Save jjhiggz/85dcba596c54c7427537cdd48f4e6bae to your computer and use it in GitHub Desktop.
Save jjhiggz/85dcba596c54c7427537cdd48f4e6bae to your computer and use it in GitHub Desktop.
result
const result = <T,E extends Error>(cb: () => T): [null, E] | [T, null] => {
try {
return [cb(), null]
} catch(e){
return [null,e as E]
}
}
const failsSometimes = () => {
if(Math.random() > .5){
throw new Error("Failed")
}
return "success"
}
const [success, failed] = result(failsSometimes)
console.log({
success,
failed
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment