0.4.8 • Published 7 months ago

@nanlabs/fp v0.4.8

Weekly downloads
-
License
MIT
Repository
github
Last release
7 months ago

Documentation | Contributing

Continious Integration npm npm License: MIT

This library provides a set of tools to help you write functional code in TypeScript. It includes tools for type guards, error handling, and more!

Installation

npm install @nanlabs/fp

Usage

The following example shows how some of the multiple tools provided by this library can be used.

You can find more examples in the documentation.

Type Guards

The following example shows how to use Rule Sets to create type guards. We can use isType to check if a value matches a Rule Set.

import { isString, isNumber, isType } from "@nanlabs/fp";

const userRuleSet = {
  username: isString,
  email: isString,
  age: isNumber,
};

const isUser = (value: unknown): value is User => isType(value, userRuleSet);

const user: unknown = { username: "John", email: "jonh@gmail.com", age: 30 };

if (isUser(user)) {
  // user is User
}

Either and Error Handling

The following example shows how to use Either to handle errors. We can use isLeft and isRight to check if an Either is Left or Right.

import { Either, left, right } from "@nanlabs/fp";

const div = (x: number): Either<Error, number> => {
  if (x === 0) {
    return left(new Error("Division by zero"));
  }

  return right(1 / x);
};

const divResult = div(0);

if (divResult.isLeft()) {
  // divResult is Left
  console.log(divResult.value.message);
}

if (divResult.isRight()) {
  // divResult is Right
  const result = divResult.value;
  console.log(result);
}
0.4.8

7 months ago

0.4.7

12 months ago

0.4.6

12 months ago

0.4.5

1 year ago