Skip to content

SimonHarmonicMinor/try-monad

Repository files navigation

Try Monad

Typescript Try monad

Status

npm (scoped) Build Status Coverage Code Smells Bugs NPM

Quick Start

npm install @kirekov/try-monad

or

yarn add @kirekov/try-monad

Usage

The monad purpose is to build a pipeline of computations that might fail.

import Try from '@kirekov/try-monad';

const result =
    Try.of(() => fetchUserCard(userId))
       .filter(card => card.isAccessible)
       .map(card => ({login: card.login, name: card.name, lastName: card.lastName}))
       .flatMap(card => Try.of(() => withUserPermissions(card)))
       .orElse(STUB_USER_CARD);

The monad acts lazily. So, all computations deffer until terminal operations call (orElse, orElseGet, orElseThrow).

const tryMonad =
    Try.of<UserDTO>(() => JSON.parse(value))
       .map(user => {
         console.log('parsed user', user);
         return user.name;
       });
const name = tryMonad.orElse('default name');
// print happens after 'orElse' call

Besides, it is possible to retrieve the first succeeded result.

const tryMonad =
    Try.of<string>(() => {
      throw new Error();
    }).orElseTry(() => "right token")
      .orElseTry(() => "wrong token");
const token = tryMonad.orElse("default");
// token === 'right token'