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

@cahmoraes93/either

v1.0.5

Published

This package implements The Monad Either

Downloads

9

Readme

Monad Either

Either is a set of functions to generate a monad, the Either monad. Its role is to elegantly handle situations that can generate an error.

Using TypeScript features, this package is able to perform type guard through Type Predicate.

The isLeft() and isRight() methods were made using Type Predicate features to refine TypeScript's type-safety and ensure type safety.

Read more: Advanced Types

How it works: Either literally means OR one thing OR the other. You can define that a method can return some types of error or some types of success. Error types are on the left and success types are on the right. For example, in the case of creating an email, the method that creates the email can return InvalidEmailError OR the object of type Email successfully created.

It is possible to know if the returned type was error or success by asking if it is "right" or "left". That is, if it is "left" it is a type of error, if it is "right" it is a type of success.

  • EitherType<L, R>: Type alias to set a method return to Either. The type variable "L" defines the types of errors separated by pipes "|" and the type variable "R" defines the success type.

    This type is only used to define the return type of a functions that will return an "Either" e.g. (Left or Right)


Left<L, R>

Constructor function that returns an Either instance of type Left.

property

- value: L
  // Returns the wrapped value

methods:

- isLeft(): boolean
  // Returns true when instance is type of Left
- isRight(): boolean
  // Returns false when instance is not type of Left

Right<L, R>

Constructor function that returns an Either instance of type Right.

property

- value: R
  // Returns the wrapped value

methods:

- isLeft(): boolean
  // Returns false when instance is type of Right
- isRight(): boolean
  // Returns true when instance is not type of Right

Factories Left and Right

- Either.left<L, R>(aValue: L): Left<L, R>

Factory function to build an Either object of type Left.

- Either.right<L, R>(aValue: R): Right<L, R>

Factory function to build an Either object of type Right.


Example using left and right

import { Either, EitherType } from '@cahmoraes93/either'

function doThing(): EitherType<EvenNumberException, number> {
  const randomNumber = Math.floor(Math.random() * 10)

  if (randomNumber % 2 === 0) {
    // Either.left to return an Error/Exception
    return Either.left(new EvenNumberException(randomNumber))
  }
  // Either.right to return success
  return Either.right(randomNumber)
}

const result = doThing()

Usage Example

import { Either, EitherType } from '@cahmoraes93/either'

class InvalidEmailError extends Error {...}
class InvalidLengthError extends Error {...}

function createEmail(): EitherType<InvalidEmailError | InvalidLengthError, string> {
  const email = service.generateRandomEmail()

  if (!email.includes('@')) {
    return Either.right(
      new InvalidEmailError(`The email is too short ${email}`)
    )
  }

  if (email.length < 5) {
    return Either.left(
      new InvalidLengthError(`The email is too short ${email}`)
    )
  }

  return Either.right(email)
}

  const emailOrError = createEmail()

  if (emailOrError.isLeft()) {
    // handle the error in the best way
    console.error(emailOrError.value.message)
  }

  /*
    from this point the email is valid, it is possible to omit the emailOrError.isRight() call
  */

  if (emailOrError.isRight()) {
    console.log(emailOrError.value)
  }