Skip to content

Porting some excellent design implementations from Rust to JavaScript.

License

Notifications You must be signed in to change notification settings

JiangJie/happy-rusty

Repository files navigation

Use Rust features in JavaScript happily

NPM version NPM downloads JSR Version JSR Score Build Status codecov


[中文]


Partial supported

More is coming

Installation

via pnpm

pnpm add happy-rusty

or via yarn

yarn add happy-rusty

or just from npm

npm install --save happy-rusty

via JSR

jsr add @happy-js/happy-rusty

for deno

deno add @happy-js/happy-rusty

for bun

bunx jsr add @happy-js/happy-rusty

then import to your code.

import { Some, None, Ok, Err } from 'happy-rusty';

Enjoy the happiness.

Examples

import { Some, None, Ok, Err } from 'happy-rusty';

function judge(n: number): Option<Promise<Result<number, Error>>> {
    if (n < 0 || n >= 1) {
        return None;
    }

    return Some(
        new Promise((resolve) => {
            const r = Math.random();
            resolve(r > n ? Ok(r) : Err(new Error('lose')));
        })
    );
}

const res = judge(0.8);
if (res.isNone()) {
    console.error('invalid number');
} else {
    const result = await res.unwrap();
    if (result.isErr()) {
        console.assert(result.err().message === 'lose');
    } else {
        console.log(result.unwrap()); // must greater than 0.8
    }
}