Minimum option type port of Rust.
This project provides minimum option features. They are designed to be optimized in tree-shaking.
One of the existing challenges in the JavaScript/TypeScript community is tree-shaking. Due to the dynamic nature of the language, tree-shaking can only be used in limited situations. That is, tree-shaking cannot do anything about unused class methods or properties.
The only solution to this is separation into top-level functions. It is very unfortunate but true that no other method exists.
Having said that, a future proposal could solve this.
deno.land:
import * as mod from "https://deno.land/x/optio/mod.ts";
npm:
npm i @miyauci/option
Type Option represents an optional value.
Every Option is either Some and contains a value, or None, and does not.
import {
expect,
None,
type Option,
Some,
} from "https://deno.land/x/optio/mod.ts";
function divide(numerator: number, denominator: number): Option<number> {
if (!denominator) return None;
return Some(numerator / denominator);
}
const opt = divide(100, 0);
expect(opt, "divide by 0");
All operators for Option are separated from prototype.
The pipeline operator will linearize the nesting.
import { map, type Option, match } from "https://deno.land/x/optio/mod.ts";
declare const option: Option<unknown>;
declare const mapper: (value: unknown) => unknown
const result = map(option, mapper)
|> map(%, mapper)
|> match(%, {
Some: mapper,
None:mapper
})
proposal extensions allows for successive function adaptations, as in the Fluent API.
import { map, type Option, match } from "https://deno.land/x/optio/mod.ts";
declare const option: Option<unknown>;
declare const mapper: (value: unknown) => unknown
const result = option
::map(mapper)
::map(mapper)
::match({
Some: mapper,
None: mapper
})
See deno doc for all APIs.
See contribution.
MIT © 2023 Tomoki Miyauchi