Results
Small and tree-shakeable Result/Option implementation.
Option
compare with Rust by Example
import type { } from '@moeru/results'
import { , as , } from '@moeru/results'
const = (: number, : number): <number> =>
=== 0
?
: ( / )
const = (: number, : number) =>
.(
(, ),
=> `${} / ${} = ${}`,
() => { throw new (`${} / ${} failed!`) },
)
const = () => {
(4, 2) // "4 / 2 = 2"
(1, 0) // throw error
const = (0)
.(`${} unwraps to ${.()}`)
.(`${} unwraps to ${.()}`) // throw error
}Result
compare with Rust by Example
import type { } from '@moeru/results'
import { , , as } from '@moeru/results'
enum {
= 'DivisionByZero',
= 'NegativeSquareRoot',
= 'NonPositiveLogarithm',
}
type = <number, >
const = (: number, : number): =>
=== 0
? (.)
: ( / )
const = (: number): =>
< 0
? (.)
: (.())
const = (: number): =>
<= 0
? (.)
: (.())
const = (: number, : number): number =>
.(
(, ),
=> .(
(),
=> .(
(),
=> ,
() => { throw },
),
() => { throw },
),
() => { throw },
)
const = () =>
.((1, 10))Methods
Most of the methods are the same as in Rust.
We provide different import points for Option and Result:
import { as , as } from '@moeru/results'
// import * as o from '@moeru/results/option'
// import * as r from '@moeru/results/result'
.(.())
.(.())extract
Extracted values or errors.
import type { , } from '@moeru/results'
import { as , , as , } from '@moeru/results'
.(('foo') as <string>) // string | undefined
.(('bar') as <string, Error>) // string | Errorfrom
Convert common types / function results to Option or Result.
import { as , as } from '@moeru/results'
.('foo' as 'foo' | undefined) // Option<'foo'>
export const = (: string) =>
.(() => new ()) // Result<string, Error>wrap
You can achieve something like the question mark operator in Rust.
Let's modify the Result Example above to use wrap / unwrap instead of match:
const op = (x: number, y: number): number =>
r.match(
- div(x, y),
- radio => r.match(
- ln(radio),
- ln => r.match(
- sqrt(ln),
- sqrt => sqrt,
- (err) => { throw err },
- ),
- (err) => { throw err },
- ),
+ r.wrap(() => {
+ let _ratio = unwrap(div(x, y))
+ let _ln = unwrap(ln(_ratio))
+ return sqrt(_ln)
+ }),
+ (value) => value,
(err) => { throw err },
)