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

monads-typescript

v1.1.1

Published

Monadic types for Typescript

Downloads

5

Readme

monads-typescript

In functional programming, a monad is a design pattern that allows structuring programs generically while automating away boilerplate code needed by the program logic.

In a strongly typed liked language like Scala, with built-in types like the Option type, you are very likely to have already used or will eventually end up using monads without even knowing you are using them. This project is my attempt at understanding monads by writing them, and I decided to use TypeScript because it forces me to build monads from "scratch", but with support for strong typing.

Installation

npm i monads-typescript

Usage

Import the appropriate static methods from the library like so:

import { left, right } from 'monads-typescript';
import { maybe } from 'monads-typescript';
...

Maybe Monad

The first monad, the Maybe monad, is based on Scala's Option type. It's very useful when you want to encapsulate computation on values that might be null or undefined.

Here's an example of some code you might find yourself writing in JavaScript/TypeScript:

const greetUser = (userId) => {
  const user = getUser(userId);
  let name;
  if (user) {
    name = user.getName();
  }
  if (name) {
    return `Hello ${name}`;
  } else {
    return 'Hello, guest';
  }   
}

Using the Maybe monad:

const greetUser = (userId: number) => {
  return maybe(getUser(userId))
    .map((user) => user.getName())
    .map((name) => `Hello, ${name}`)
    .getOrElse('Hello, guest');
};

Depending on your application, you could simplify this even further, like so:

const getName = (user: User) => user.getName();
const greetName = (name: string) => `Hello, ${name}`;

const greetUser = (userId: number) => {
  return maybe(getUser(userId))
    .map(getName)
    .map(greetName)
    .getOrElse(greetName('guest'));
};

As you can see, using the Maybe monad abstracts away a lot of boilerplate, giving you a flat, composable interface to work with that's much more readable.

Either Monad

Similarly, the Either monad is based on Scala's Either type.

The Either monad is useful when you want to represent one of two possible types. An instance of Either is either a Left or Right. By convention, Right is used to represent a success type, while Left is used to hold a failure type.

Here's another example of some code you might write in imperative TypeScript:

const getAge = (uid: number): number | never => ...;
const canDrink = (age: number): boolean => age >= 18;

const okToDrink = (uid: number) => {
  try {
    const age = getAge(uid);
    if (age) {
      return canDrink(age);
    } 
  } catch {
    return false;
  }
} 

Rewriting this using the Either monad:

const getAge = (uid: number): Either<string, number> => ...; // the left represents an error string
const canDrink = (age: number): boolean => age >= 18;

const okToDrink = (uid: number) => {
  getAge(uid).fold(
    (error) => {
      console.log(`Error getting age: ${error}`);
      return false;
    },
    (age) => canDrink(age)
  )
}

Resources

Other JavaScript/TypeScript implementations

  • monad.js, a vanilla JavaScipt implementation of Maybe and Either monads
  • TsMonad, a TypeScript implementation of Maybe, Either and Writer monads