0.0.1 • Published 2 years ago

@dubsar/result v0.0.1

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

@dubsar/result

A Result expression in javascript.

Features

  • Simple but full-featured API
  • No dependencies
  • Includes a TypeScript declaration file

The library mimics rust's Result with three main goals:

  • keep it simple
  • pattern matching syntax as close as possible to rust's
  • expression language features

Load

Browser:

<script type="module">
  import {Result} from './path/to/result.mjs';
  ...
</script>

Node.js:

npm install @dubsar/result
const { Result } = require("@dubsar/result");

import { Result } from "@dubsar/result";

Use

Result has two builders, and no constructor:

  • ok: to hold the successful result of a computation
const success: Result<String> = Result.ok("Hello");
  • error: to hold the error produced by an unsuccessful computation
const failure: Result<Error> = Result.error("Something webt wrong");

Pattern matching is achieved by the expression method match:

interface Api {
  fetchItem: () => Result<Item>;
}

const items = (api: Api): Item[] =>
  api.fetchItem().match(
    (item) => [item],
    (error) => {
      console.error(`Something went wrong: ${error.message}`);
      return [];
    },
  );

An ergonomic feature is that the error handler is optional.

If a function returns a Result and wants the caller to handle errors just omit the second argument and the error will be handled upstream.

Licence

The MIT Licence (Expat).

0.0.1

2 years ago