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 🙏

© 2025 – Pkg Stats / Ryan Hefner

ts.data.either

v3.0.0

Published

A Typescript implementation of the Either data type

Readme

Either

Build Status npm version

The Either data type encapsulates the idea of a computation that may fail.

An Either value can either be Right some value or Left some error.

type Either<T> = Right<T> | Left;

Install

npm install ts.data.either --save

Example

import { Either, tryCatch, andThen, withDefault } from './either';

interface UserJson {
  id: number;
  nickname: string;
  email: string;
}

// throws if file does not exists
const readFile = (filename: string): string => {
  const fileSystem: { [key: string]: string } = {
    'something.json': `
    [
      {
        "id": 1,
        "nickname": "rick",
        "email": "[email protected]"
      },
      {
        "id": 2,
        "nickname": "morty",
        "email": "[email protected]"
      }
    ]`
  };
  const fileContents = fileSystem[filename];
  if (fileContents === undefined) {
    throw new Error(`${filename} does not exists.`);
  }
  return fileContents;
};

// Wraps the read file operation in an Either
const readFileContent = (filename: string): Either<string> =>
  tryCatch(
    () => readFile(filename),
    err => err
  );

// Wraps the json parsing operation in an Either
const parseJson = (json: string): Either<UserJson[]> =>
  tryCatch(
    () => JSON.parse(json),
    err => new Error(`There was an error parsing this Json.`)
  );

// The pipeline function just makes function invocations flow
const pipeline = (initialValue: any, ...fns: Function[]) =>
  fns.reduce((acc, fn) => fn(acc), initialValue);

const usersFull: UserJson[] = pipeline(
  'something.json',
  (fname: string) => readFileContent(fname),
  (json: Either<string>) => andThen(parseJson, json),
  (users: Either<UserJson[]>) => withDefault(users, [])
); // returns the Array of users because all intermediate operations have succeeded

const usersEmpty: UserJson[] = pipeline(
  'nothing.json',
  (fname: string) => readFileContent(fname),
  (json: Either<string>) => andThen(parseJson, json),
  (users: Either<UserJson[]>) => withDefault(users, [])
); // returns an empty Array because the readFile operations failed

Api

(Inspired by elm-lang)

right

right<T>(value: T): Either<T>

Wraps a value in an instance of Right.

right(5); // Right<number>(5)

left

left<T>(error: Error): Either<T>

Creates an instance of Left.

left(new Error('Something bad happened')); // Left<unknown>(Error('Something bad happened'))
left<number>(new Error('The calculation failed')); // Left<number>(Error('The calculation failed'))

isRight

isRight<T>(value: Either<T>): boolean

Returns true if a value is an instance of Right.

isRight(left(new Error('Wrong!'))); // false

isLeft

isLeft<T>(value: Either<T>): boolean

Returns true if a value is not an instance of Right.

isLeft(right(5)); // false
isLeft(left('Hi!')); // true
isLeft(null); // true

withDefault

withDefault<T>(value: Either<T>, defaultValue: T): T

If value is an instance of Right it returns its wrapped value, if it's an instance of Left it returns the defaultValue.

withDefault(right(5), 0); // 5
withDefault(left(new Error('Wrong!')), 0); // 0

caseOf

caseOf<A, B>(caseof: {Right: (v: A) => B; Left: (err: Error) => B;}, value: Either<A>): B

Run different computations depending on whether an Either is Right or Left and returns the result.

caseOf(
  {
    Left: err => `Error: ${err.message}`,
    Right: n => `Launch ${n} missiles`
  },
  right('5')
); // 'Launch 5 missiles'

map

map<A, B>(f: (a: A) => B, value: Either<A>): Either<B>

Transforms an Either value with a given function.

const add1 = (n: number) => n + 1;
map(add1, right(4)); // Right<number>(5)
map(add1, left(new Error('Something bad happened'))); // Left('Something bad happened')

tryCatch

tryCatch<A>(f: () => A, onError: (e: Error) => Error): Either<A>

Transforms a function (that might throw an exception) that produces A to a function that produces Either<A>.

tryCatch(
  () => JSON.parse(''),
  err => err
); // Left('Unexpected end of JSON input')

andThen

andThen<A, B>(f: (a: A) => Either<B>, value: Either<A>): Either<B>

Chains together computations that may fail.

const removeFirstElement = <T>(arr: T[]): T[] => {
  if (arr.length === 0) {
    throw new Error('Array is empty');
  }
  return arr.slice(1);
};

const safeRemoveFirst = <T>(arr: T[]): Either<T[]> => {
  try {
    return right(removeFirstElement(arr));
  } catch (error) {
    return left(error);
  }
};

// The pipeline function just makes function invocations flow
const pipeline = (initialValue: any, ...fns: Function[]) =>
  fns.reduce((acc, fn) => fn(acc), initialValue);

const result: string[] = pipeline(
  ['a', 'b', 'c'],
  safeRemoveFirst, // Right(['b', 'c'])
  (arr: Either<string[]>) => andThen(safeRemoveFirst, arr), // Right(['b'])
  (arr: Either<string[]>) => andThen(safeRemoveFirst, arr), // Right([])
  (arr: Either<string[]>) => andThen(safeRemoveFirst, arr), // Left(Error('Array is empty'))
  (arr: Either<string[]>) => andThen(safeRemoveFirst, arr), // Left(Error('Array is empty'))
  (arr: Either<string[]>) => withDefault(arr, [])
);

console.log(result); // []