Created
August 15, 2024 04:08
-
-
Save jjhiggz/85dcba596c54c7427537cdd48f4e6bae to your computer and use it in GitHub Desktop.
result
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
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