Result Monad adaptation for easy usage in JavaScript
npm install kekkaA set of monad objects to simplify and clarify your business logic:
- Result
- Optional
The first object is the Result Object inspired by Rust Result Monad. The second is the java inspired Optional.
Never felt that something was missing in Javascript way of managing errors ?
A middle ground between returning undefined for business reasons and throwing Errors for business reasons.
``js`
getUser(userId) // returns undefined if no user found
.then((user) => {
if(!user) {
// do stuff knowing user was not found
}
})`
Or throwing errors for business reasons ?js`
getUser(userId) // returns undefined if no user found
.catch((error) => {
if(error instanceof NoUserFoundError) {
// do stuff knowing user was not found
}
})
Ever heard about Railway Programming ? or the Rust Result Monad ?
Wanting something like that in Javascript ? I did ! Enter the Result class.
Tired of writing endless guard clauses like
`js`
if(!userName) {
return
}`
or js`
if(user && user.name) {
// do something
}
Maybe want more elegant and explicit way to signal optional values in your business logic ?
Look out for the Optional` class
- v4.0: Add Optional Object
- v3.0: Fix broken import from different modules in mono-repo
- v2.0: Transcription to Typescript
- Typescript Types
- Suppression of enableResultPromiseHelpers function
- Removal of support for non-native promises
Result Object Documentation
- Result Class
- Build a Result
- Check Result type
- Get the associated value
- Work only on successful value
- Using with promises
- Configuration
- thenOnSuccess and thenOnFailure
Optional Object Documentation
- Optional Class
- Build an Optional
- Check Optional state
- Unwrap the optional value
- Work only if optional has value
- Using with Result Objects
- Optional.toResult
- Result.toOptional
There is a chai plugin available to make sweeter assertions: chai-kekka.