unbyte / reop

The Result and Option for Javascript/Typescript.

Home Page:https://www.npmjs.com/package/reop

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

ReOp

npm GitHub Codecov GitHub Workflow Status

The Result and Option for Javascript/Typescript.

Documentation

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()

About

The Result and Option for Javascript/Typescript.

https://www.npmjs.com/package/reop

License:MIT License


Languages

Language:TypeScript 99.9%Language:Shell 0.1%