Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/fatmatto/resultjs
Result monad for Javascript
https://github.com/fatmatto/resultjs
Last synced: 1 day ago
JSON representation
Result monad for Javascript
- Host: GitHub
- URL: https://github.com/fatmatto/resultjs
- Owner: fatmatto
- Created: 2021-08-23T09:14:17.000Z (over 3 years ago)
- Default Branch: main
- Last Pushed: 2023-11-27T16:11:44.000Z (about 1 year ago)
- Last Synced: 2025-01-06T23:39:36.387Z (21 days ago)
- Language: JavaScript
- Size: 132 KB
- Stars: 2
- Watchers: 3
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- Changelog: CHANGELOG.md
Awesome Lists containing this project
README
## Result Monad
Convenient way to handle functions that might return errors without throwing. Heavily inspired by Rust and Golang.
### Usage
```javascript
const {wrap, wrapSync} = require('@fatmatto/resultjs')
// Wrap an async function that might throw
const wrapped = wrap(params => mightFailAsync(params))// Wrap a sync function
const wrappedSync = wrapSync(params => mightFail(params))const result = await wrapped(someParams)
if (result.isError()) {
// True if result holds an error
}if (result.isOk()) {
// True if result does not holds an error but holds a value
}// Throws if result holds an error or returns the value if it contains a value
const value = result.unwrap()// Returns the value if result holds the value, or the backup value if it holds an error
const altValue = result.unwrapOr('someBackupValue')// Turns the Result instance into an array
const [error, value] = result.toArray()if (error) {
// handle the error
}// Destructuring values
const {error,value} = resultconst mightBeAnError = someFunction()
// Create a Result instance from a value which might be an error
const result = Result.from(mightBeAnError)
if (result.isError()) {
// handle error
}```
### Shortcuts
```javascript
const {ok,err} = require('@fatmatto/resultjs')// Shortcut for new Result(null,v)
const result = ok(imSureThisIsAGoodValue)// Shortcut for new Result(error,null)
const result = err(error)
```