npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

resultat

v1.0.11

Published

## Description

Downloads

22

Readme

Resultat - Typed Result Handling for JS/TS

Description

Resultat is a TypeScript library designed to simplify error handling and provide a structured approach for dealing with success and error scenarios. The library introduces a custom Result type along with utility functions to deal with the outcome. By leveraging Resultat, you can enhance the reliability and clarity of error handling in your TypeScript projects.

Installation

To start using Resultat in your TypeScript project, you can install it via npm or yarn:

npm install resultat

# or

yarn add resultat

Usage Example: Dividing Two Numbers

Consider a simple use case of dividing two numbers. The divideNumbers function returns either an Ok result containing the division result or an Err result with an error message if division by zero occurs.

import { Ok, Err } from "resultat";
import type { Result } from "resultat";

// Simple example: Divide Two Numbers
function divideNumbers(a: number, b: number): Result<number> {
  return b === 0 ? Err("Cannot divide by 0") : Ok(a / b);
}

Unpacking result.ok

Before retrieving the value from the result, you have to confirm whether the result returned Ok or Err, using type narrowing. Here's how you can achieve this:

const result = divideNumbers(10, 0);

if (result.ok) {
  console.log("Division result:", result.val);
} else {
  // Handle the Err case
  console.error("Error:", result.err);
}

unwrap: Extracting Values from Ok

The unwrap function allows you to extract the value from an Ok result. If the result is an Err, it throws an error. Use it when you need to assert that result is Ok.

// Success
const result = divideNumbers(10, 2);
const value = result.unwrap(); // Returns 5

// Failure
const result = divideNumbers(10, 0);
const value = result.unwrap(); // Throws the error

unwrapOr: Providing a Default Value

The unwrapOr function extracts the value from an Ok result or returns a provided default value if the result is an Err. This is useful when you want to ensure a fallback value in case of errors.

const result = divideNumbers(10, 0);
const num = result.unwrapOr(0); // Returns 0 since division by 0 results in an Err

unwrapOrElse: Providing a Callback

The unwrapOrElse function is used to extract the value from an Ok result or execute a provided callback to handle the Err result and provide a fallback value.

const result = divideNumbers(10, 0);
const num = result.unwrapOrElse((errorMessage) => {
  console.error(errorMessage, "Defaulting to 0");
  return 0; // Fallback value provided by the callback
});

Realistic Example: Retrieving User Data with Error Handling

In real-world applications, fetching user data from a database or API can result in various outcomes. The Result type provided by Resultat can simplify error handling and result management. Consider the following example:

Function Explanation

The following function attempts to retrieve user data based on a provided username.

  • If a user is found, the function returns an Ok result containing the user object.
  • If no user is found, the function returns an Err result indicating that the user was not found.
  • If UserModel.findByUsername throws, the function returns an Err result with a generic error message.
function findUser(username: string) {
  try {
    const user = UserModel.findByUsername(username);
    if (user === null) {
      return Err("User not found");
    }
    return Ok(user);
  } catch (e) {
    return Err("Something went wrong");
  }
}

Annotating Return Types with Resultat

Resultat allows you to annotate return types explicitly, ensuring clarity in intentions and type of the ResultOk and ResultErr path.

type UserData = {
  name: string;
  isAdmin: boolean;
};

function findUser(username: string): Result<UserData, string> {
  if (x === 1) {
    return Err("Error 1");
  }
  if (x === 2) {
    return Err("Error 2");
  }
  return Ok({ name: "John", isAdmin: false ));
}