2.0.6 • Published 2 years ago

resultt v2.0.6

Weekly downloads
-
License
MIT
Repository
github
Last release
2 years ago

CircleCI

ResultT

ts/js users cannot use try-catch as expression so that we have to struggle with complicated runtimes.

ResultT is type-safe runtime wrapping library. Strongly inspired by Kotlin Result implementation.

Install

From npm registry...

npm i resultt

type declaration is included.

class import...

import { Resultt } from 'resultt';

Usage

Try to start from runCatching method. This wraps the result of success or failure.

// sample logic and response interface
interface Response {
    data: string
}
class Service {
    execute(value: string): Response {
    return {data: value};
    }
}

// execute some function and wrap by "runCatching"
const result: Result<Response> = Result.runCatching(() => {
        return new Service().execute('execution');
    })
    .onSuccess((v) => {
        console.log(`response => ${v}`);
        return v
    });
    .onFailure((it: Error) => {
        console.error(it);
        return {
            data: 'DEFAULT'
        };
    });

// You may get the value of execute by "get" functions as declarative.
const v1 = result.getOrThrow();  // => success ... { data: execution }
const v2 = result.getOrDefault({
    data: 'OTHER'
});

// You can process as commandly.
let v;
if (result.isSuccess()) {
    v = result.getOrThrow();
}

// Map the result to another map by fold.
const folded: number = Result.runCatching(() => {
        return new Service().execute('execution');
    })
    .fold(
        (data: Response) => {
            console.log(data);
            return data.data.length;
        },
        (it: Error) => {
            console.log(it);
            return 0;
        },
    );
console.log(folded);  // => 9

// Or, shorthand for fold with getOrElse
const n: number = Result.runCatching(() => {
        return new Service().execute('execution');
    })
    .getOrElse((it: Error) => {
            console.log(it);
            return 0;
        },
    );
console.log(n);  // => 9

For more info...

Full class documentation is here: docs

2.0.5

2 years ago

2.0.4

2 years ago

2.0.6

2 years ago

2.0.3

3 years ago

2.0.2

3 years ago

2.0.1

3 years ago

2.0.0

3 years ago

1.0.6

3 years ago

1.0.5

3 years ago

1.0.4

3 years ago

1.0.3

3 years ago

1.0.2

3 years ago

1.0.1

3 years ago

1.0.0

3 years ago