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

ghetto-monad

v2.1.2

Published

Either and Maybe monad-like patterns using TypeScript type guards

Downloads

21

Readme

Ghetto Monad

Monad-inspired patterns using TypeScript type guards to enforce null-safety and error handling via the type system.

Version 2: Version 2 of the library is backward-compatible with Version 1, but provides first-class objects.

Installing

Install from npm:

npm i ghetto-monad

Either

The Either type uses type guards to enforce error handling before allowing access to a return value. Use it when a function may return either an Error or a result.

import {Either, ErrorResult, Result} from 'ghetto-monad';

function errorOrString(jsonString: string): Either<ErrorResult<Error>, Result<object>> {
    try {
        return new Result(JSON.parse(jsonString));
    } catch (e) {
        return new ErrorResult(e);
    }
}

const result = errorOrString(something);

if (result.isError) {
    console.log(result.error); // .error property available
} else {
    console.log(result.value); // .value property available
}

Typed Errors with ErrorResult<T>

Sometimes a function can return an Error. The ErrorResult type can wrap an Error, and provides metadata on the type of error, allowing you to communicate to consuming code the types of error that can be returned.

This is similar to the Java construct throws (see: Specifying the Exceptions Thrown by a Method).

You don't have to use it, in which case just use ErrorResult<Error> everywhere.

If you do want error typings, then you need to create wrappers for errors.

For example, if your code can return a NotImplementedError or a ValidationError, then you declare classes for each of these Error types, extending Error. Then you can specify part of your return as ErrorResult<NotImplementedError | ValidationError>.

You need to implement your typed errors so that you can test them in consuming code using instanceof. So:

export class NotImplementedError implements Error {
	name: string; message: string;
	stack?: string | undefined;
	constructor(error: Error) {
		this.name = error.name;
		this.message = error.message;
		this.stack = error.stack;
	}
};

export class ValidationError implements Error {
	name: string; message: string;
	stack?: string | undefined;
	constructor(error: Error) {
		this.name = error.name;
		this.message = error.message;
		this.stack = error.stack;
	}
};

And return errors like this:

const coinToss = () => Math.random() > 0.5 ? "heads" : "tails";

function errorOrResult(): Either<ErrorResult<NotImplementedError | ValidationError>, Result<number>> {
    if (coinToss() === "heads") {
        return new Result(Math.random());
    }
    if (coinToss() === "heads") {
        return new ErrorResult(new NotImplementedError(new Error("Not implemented (yet)!")))
    }
    return new ErrorResult(new ValidationError(new Error("Validation Error")));
}

Then in the consuming code you can test the ErrorResult like this:

const result = errorOrResult();
if (result.isError) {
    if (result.error instanceof NotImplementedError) {
        // NotImplementedError
    } else {
        // ValidationError
    }
} else {
    console.log(result.value);
}

Maybe

The Maybe type uses type guards to enforce handling an undefined or null value before accessing the value. Use it when a function return value maybe null or undefined.

import {Maybe, Nothing, Result} from 'ghetto-monad';

function stringOrNothing(jsonString: string): Maybe<Result<string>>> {
    if (Math.random() > 0.5) {
        return new Nothing();
    } else return new Result<string>("Success!");
}

const result = stringOrNothing();

if (result.isNothing) {
    console.log("Nothing returned!");
} else {
    console.log(result.value); // .value property available
}

Combining the two

import {Either, ErrorResult, Maybe, Nothing, Result} from 'ghetto-monad';

function eitherOrNothing(): Either<ErrorResult<Error>, Maybe<IResult<string>>> {
    if (Math.random() > 0.5) {
        return new ErrorResult(new Error());
    } else return new Result<string>("Success!");
}
const e = eitherOrNothing();

if (e.isError) {
    // Result is Error
    console.log(e.error);
} else {
    if (e.isNothing) {
        // Result is nothing
    } else
        console.log(e.value);
}

Deprecated Version 1 methods

Maybe

Maybe.Type<T> is a return value that is either undefined or a T.

To determine what the value is, dereference it like this:

import * as Maybe from "ghetto-monad/Maybe";

function sometimesNull(): Maybe.Type<string> {
    if (Math.random() > 0.5) {
       return "Hello";
    } else {
       return undefined;
    }
}

const result = sometimesNull();

if (Maybe.isNothing(result)) {
    // result is a undefined
} else {
    // result is undefined
}

Result

A Either-type.

Result.Type<T> is a return value that is either an Error or a T.

To determine what the value is, dereference it like this:

import * as Result from 'ghetto-monad/Result';

function sometimesError(): Result.Type<string> {
    if (Math.random() > 0.5) {
       return "Hello";
    } else {
       return new Error("Doesn't work!");
    }
}

const result = sometimesError();

if (Result.isError(result)) {
   // handle error
} else {
   // result is a string
}