1.0.0 • Published 2 years ago

my-simple-either v1.0.0

Weekly downloads
-
License
MIT
Repository
github
Last release
2 years ago

my-simple-either

Download Status Github Star Github Issues NPM version License

Simple Type and Function set for Either interface. Either important concept in functional programming. But Node.js and TypeScript not support this concept. So you can choose fp-ts or anther functional utility. But if you need only Eihter, this package is good alternative.

Why? use Either?

Helpful for functional programming and integrate return type. See below.

import { parse as jsoncParse } from 'jsonc-parser';
import { parse as json5Parse } from 'json5';

function json5Parse(value: string): SimpleEither<Error, Record<any, any>> {
  try {
    return pass(json5Parse(value));
  } catch (err) {
    return fail(new Error(err));
  }
}

function jsoncParse(value: string): SimpleEither<Error, Record<any, any>> {
  try {
    return pass(jsoncParse(value));
  } catch (err) {
    return fail(new Error(err));
  }
}

function parse(value: string): Record<any, any> {
  const jsoncParsedEither = jsoncParse(value);

  if (isPass(jsoncParsedEither)) {
    return jsoncParsedEither.pass;
  }

  const json5ParsedEither = json5Parse(value);

  if (isPass(json5ParsedEither)) {
    return json5ParsedEither.pass;    
  }

  // also you can use "throw new Error(jsoncParsedEither.fail);"
  throw new Error(json5ParsedEither.fail);
}

throw keyword move control-flow. But Either, SimpleEither don't move control-flow besides Either helpful functional programming and function pipe.

Either

Name using left and right.

namedescription
ILeftLeft interface
IRightRight interface
EitherEither type using ILeft and IRight
leftvalue convert ILeft type
rightvalue convert IRight type
isLeftcheck given value is ILeft type
isRightcheck given value is IRight type

SimpleEither

Name using pass and fail.

namedescription
IFailFail interface
IPassPass interface
SimpleEitherSimpleEither type using IFail and IPass
failvalue convert IFail type
passvalue convert IPass type
isFailcheck given value is IFail type
isPasscheck given value is IPass type

Generic type in Either, SimpleEither

First generic type is ILeft or IFail. Because fp-ts and many programming language choose first type is left(or fail).

type Either<TLEFT, TRIGHT> = ILeft<TLEFT> | IRight<TRIGHT>;