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

@kwyjibo-developments/typescript-result

v0.2.1

Published

Result pattern for typescript projects

Downloads

14

Readme

Result pattern for TypeScript

Build status npm

Motivation

In an ideal world, all method calls will execute without any failures or errors. Practically, however, method calls will sometimes fail or error due to invalid input or downstream issues with dependencies of the method (e.g. HTTP call failures). Ideally, the method will be able to advise its caller if completed its task successfully, or if there was an issue in its execution. The Result Pattern was designed to permit failures and errors to be handled by the method call, as well as provide information to the caller about the result of its computation. This package was created to provide a simple implementation of this pattern for TypeScript and JavaScript.

Without using the result pattern, typical method calls that may throw an error that needs to be handled by the parent and may need to be propagated up several parent calls to be properly handled. In the example below, we consider a method that may fail or throw an error that can be handled by its immediate parent without using Results.

function caller() : void {
    try {
        const value = callMe();
        if (value == null) {
            // handle the case where an invalid value was returned
            return; // we don't want to do more processing
        }

        // do work with value
    } catch (err) {
        // handle the error that was thrown from the computation as relevant
    }
}

function callMe() : number | null {
    // this method may throw an error
    const value = someComputation();

    if (isValid(value)) {
        return value;
    }
    // value is not valid, so return null as default to indicate failure
    return null;
}

With the use of Result objects, we can make the implementation of the caller much more straightforward and clear about exactly how it is operating using the result of callMe.

function caller() : void {

    callMe()
        .match((value) => {
            // do work with the value
        }, (theResult) => {
            // handle the case where an invalid value was returned
        },(theResult) => {
            // handle the error that was thrown from the computation as relevant
        }
    );
                
}

function callMe() : ValueResult<number> {
    try {
        // this method may throw an error
        const value = someComputation(); // returns number

        if (isValid(value)) {
            return ValueResult.Success<number>(value);
        }
        
        // value is not valid, so return a failure instance
        return ValueResult.Failed<number>("The computed value is invalid");

    } catch (err) {
        // we can now encapsulate the error in this method, so that it is
        //  not propagated up to parent methods
        return ValueResult.Error<number>(err);
    }
}

Features

  • Simple framework that provides both void and value Result implementations
  • Suitable for both JavaScript and TypeScript

Installation

npm install @kwyjibo-developments/typescript-result

Usage

import { ValueResult } from '@kwyjibo-developments/typescript-result';

function isSystemStateValid() : ValueResult<boolean> {
    try {

        // we don't control this function
        // we know it returns null if it fails, or a boolean if it
        // completes successfully
        const result = someSystemStateIsValid();

        if (result == null) {
            return ValueResult.Failed("The validation check was unable to be completed.");
        }
        
        return ValueResult.Success(result);

    } catch (err) {
        return ValueResult.Error<boolean>(err, "An unexpected error when performing the validation.");
    }
}

In the above example, it is noted here that Success and Failed do not correspond to the state of the system being measured in the someSystemStateIsValid() function. Rather, they correspond to the ability to execute the function successfully and the type of result that it returns. The outputs of this function are shown below, along with their corresponding explanations.

  • ValueResult Success with value true: The function someSystemStateIsValid completed without error and the current system state is valid.
  • ValueResult Success with value false: The function someSystemStateIsValid completed without error and the current system state is not valid.
  • ValueResult Failed: The function someSystemStateIsValid did not complete successfully. It failed with an error expected by the author of the function and returned without throwing an Error.
  • ValueResult Error: The function someSystemStateIsValid did not complete successfully. It failed with an error not expected by the author of the function and returned by throwing an Error.

The match extension method is available to provide a fluent interface for chaining the outputs of a result with future actions to perform.

import {Result, ValueResult} from '@kwyjibo-developments/typescript-result';

function doSomething() : Result { } // implementation omitted

function doSomethingElse() : ValueResult<number> { } // implementation omitted

function handler() : void {
    doSomething()                       // Line 1
        .match(
            doSomethingElse,
            failureCallback,
            errorCallback
        )
        .match(
            completeCallback,
            someOtherFailureCallback,
            someOtherErrorCallback
        );
}