krustykrab

Implementation of some helpers of Rust
stdlib on JavaScript/TypeScript
Api reference
Implemented helpers
Option
import { Some, None } from "krustykrab";
const someOption = Some("foo");
const noneOption = None();
Rust reference
krustykrab reference
Result
import { Ok, Err } from "krustykrab";
const okResult = Ok("foo");
const errResult = Err("bar");
Rust reference
krustykrab reference
Additional helpers
unwrap
Panics if the value is null
or undefined
or returns it otherwise
import { unwrap } from "krustykrab";
const fooOrUndefined = document.getElementById('foo');
const foo = unwrap(fooOrUndefined);
unwrapOr
Returns the value if it's not null
or undefined
, or returns the default value
import { unwrapOr } from "krustykrab";
const foo: Partial<Record<string, string>> = { bar: 'baz' };
unwrapOr(foo.bar, 'qux');
unwrapOr(foo.bat, 'qux');
unwrapOrElse
Returns the value if it's not null
or undefined
, or computes it
import { unwrapOrElse } from "krustykrab";
const foo: Partial<Record<string, string>> = { bar: 'baz' };
unwrapOrElse(foo.bar, () => 'qux');
unwrapOrElse(foo.bat, () => 'qux');
getResult
Converts Promise
to Result
import { getResult } from "krustykrab";
const successResult = await getResult(Promise.resolve('foo'));
successResult.unwrap();
const errorResult = await getResult(Promise.reject('bar'));
errorResult.unwrapErr();
toOption
Convert a nullable variable to Option
import { toOption } from "krustykrab";
const option = toOption('foo');
option.isNone();
option.unwrap();
toOption(null).isNone();
toOption(undefined).isNone();
tryCatch
Wrap the result of a function call with Result
import { tryCatch } from "krustykrab";
const successResult = tryCatch(() => JSON.parse('{"foo": "bar"}'));
successResult.unwrap();
const errorResult = tryCatch(() => JSON.parse("{invalid json}"));
errorResult.isErr();