0.2.5 • Published 4 years ago

@joseronierison/ts-monads v0.2.5

Weekly downloads
8
License
MIT
Repository
-
Last release
4 years ago

ts-monads

Type Script Monads

Inspired in the Scala Monads

Installation

  npm i @joseronierison/ts-monads

Runnings tests locally

  npm test

Doc

Table of contents

Option

import { Optional, Option } from "@joseronierison/ts-monads/option";

const maybeTen: Optional<number> = Option.of(10);
const maybeTwo: Optional<number> = Option.of(2);
const maybeFive: Optional<number> = Option.of(5);

const optionalOperation = 
  maybeFive
    .map(five => five * 2)
    .flatMap(v => maybeTen.map(h => h * v))
    .flatMap(v => maybeTwo.map(h => v / h));

const noneValue = Option.none();

const noneOp = maybeTen.flatMap(g => noneValue.map(n => n * g));

console.log(optionalOperation.getOrElse(0)); // 50
console.log(noneOp.getOrElse(10)); // 10

Try

import { Tryable, Try } from "@joseronierison/ts-monads/try";

const tryTen: Tryable<number> = Try.run(() => 10);
const tryFive: Tryable<number> = Try.run(() => 5);
const tryFailed: Tryable<number> = Try.run(() => { throw new Error("Something went wrong!") });

const riskOperation = 
  tryFive
    .map(five => five * 2)
    .flatMap(ten => tryTen.map(anotherTen => ten * anotherTen));

const failedOp = tryFailed.flatMap(g => tryTen.map(n => n * g));

console.log(riskOperation.getOrElse(0)); // 100
console.log(riskOperation.isSuccess()); // true

console.log(failedOp.getOrElse(10)); // 10
console.log(riskOperation.isFailure()); // true
console.log(riskOperation.getError()); // Error("Something went wrong!")

Contributing

0.2.5

4 years ago

0.2.4

4 years ago

0.2.3

4 years ago

0.2.2

4 years ago

0.2.1

4 years ago

0.2.0

4 years ago

0.1.0

4 years ago

0.0.0

4 years ago