reop
v0.3.1
Published
The Result and Option for Javascript/Typescript.
Downloads
2
Readme
The library's API is similar to Rust's, but integrates with the asynchronous language of Javascript.
Here assumes you have already known the usage of Result
and Option
in Rust,
so complicated API descriptions can be skipped,
and the uniqueness of this library can be obvious.
Consider we are looking for the entry path of a npm package, and we don't care what error occurs:
import { Result } from 'reop'
import { resolve } from 'node:path'
import { readJson, exists } from 'fs-extra'
const entry = await Option
.fromAsync(() => readJson(resolve(pkgPath, './package.json'))) // errors are caught as Option::None
.map((pkg) => resolve(pkgPath, pkg.main))
.filter((entry) => exists(entry)) // an async filter
.iter() // does the same as what Option::iter in Rust does
for (const path of entry) {
// ...
}
Or using wrap
helpers:
const readJsonOptional = Option.wrapAsync(readJson) // like what promisify() does
const entry = await readJsonOptional(resolve(pkgPath, './package.json'))
.map((pkg) => resolve(pkgPath, pkg.main))
.filter((entry) => exists(entry))
.iter()