purify-ts

repository·master·Indexed 23 days ago

https://github.com/gigobyte/purify

A functional programming standard library for TypeScript (version 2.1.4) that provides type-safe patterns and abstractions. It is Fantasy Land conformant and includes tools such as the Either and EitherAsync types for error handling, as well as a Codec interface for data transformation, validation, and JSON Schema generation.

Tokens
5.7K
Snippets
3
Records
52
Agent score
81%

What's inside purify-ts

  1. Install purify-ts via npm or yarn

    master

    Purify is available as an npm package. You can install it using your preferred package manager to start using functional programming patterns in your TypeScript project.

    $ npm install purify-ts
    $ yarn add purify-ts
  2. Use the Maybe type for optional values

    master

    The Maybe<T> type is a container used to represent an optional value that may or may not exist. It has two states:

    • Just(value): Represents a present value of type T.
    • Nothing: Represents the absence of a value.

    This type provides a functional way to handle nullability and optionality without explicit null checks, using methods like map, chain, and orDefault to transform or recover values safely.

  3. Use the Either type for error handling

    master

    The Either<L, R> type represents a value that can be one of two types: Left (conventionally used for errors or failures) or Right (conventionally used for successful values). It provides a functional way to chain computations and handle errors without using try/catch blocks everywhere.

    Key methods for transforming values:

    • map(f): Transforms the Right value if present.
    • mapLeft(f): Transforms the Left value if present.
    • bimap(f, g): Transforms both Left and Right values using different functions.
    • chain(f): Chains computations that return another Either (monadic bind).
    • caseOf(patterns): Performs structural pattern matching.

    To create an Either, use the Left and Right constructors.

  4. How MaybeAsync works and handles failures

    master

    MaybeAsync<T> is a type that represents an asynchronous computation resulting in a Maybe<T>. It extends PromiseLike<Maybe<T>>.

    Failure Semantics: When calling .run(), the resulting Promise<Maybe<T>> will resolve to Nothing in the following cases:

    1. Any computation inside the MaybeAsync resolves to Nothing.
    2. Any of the internal promises are rejected.
    3. An exception is thrown during execution.

    If no failures occur, it returns a promise resolved to a Just containing the value.

    Key Methods for Control Flow:

    • run(): Executes the computation and returns Promise<Maybe<T>>.
    • map<U>(f: (value: T) => U): Transforms the value if it is a Just. If Nothing, the mapping function is skipped and the result is Nothing.
    • chain<U>(f: (value: T) => PromiseLike<Maybe<U>>): Chains another asynchronous Maybe operation. Similar to Maybe#chain but handles promises.
    • orDefault(defaultValue: T): Returns the defaultValue if the result is Nothing, otherwise returns the unwrapped value.
    • filter<U extends T>(pred: (value: T) => value is U | (value: T) => boolean): Returns this if the predicate passes, otherwise returns Nothing.
  5. Combine codecs with oneOf, nullable, and optional

    master

    Purify provides combinators to build complex validation logic from simple codecs:

    • oneOf(...codecs): Returns a codec that succeeds if any of the provided codecs succeed. If all fail, it returns a combined error message.
    • nullable<T>(codec): A codec that accepts either the provided codec or null.
    • optional<T>(codec): A codec that accepts either the provided codec or undefined. This is specifically designed for use within Codec.interface to mark properties as optional.
    • intersect(codecA, codecB): Creates an intersection. For objects, it merges the results of both codecs.
  6. Perform predicate tests on Tuples

    master

    You can test the contents of a tuple using every and some:

    • every(pred): Returns true if the predicate pred returns true for both elements.
    • some(pred): Returns true if the predicate pred returns true for at least one element.
  7. Use fanout to construct tuples from a single value

    master

    The fanout method allows you to derive a tuple from a single input value using two different transformation functions. It supports three different usage patterns:

    1. Immediate execution: Pass two functions and a value to get a Tuple immediately.
    2. Function composition: Pass two functions to get a new function that accepts a value and returns a Tuple.
    3. Curried composition: Pass one function to get a higher-order function for building complex pipelines.
  8. Create an object codec with Codec.interface

    master

    Use Codec.interface to define a codec for a structured object by providing a mapping of property names to their respective codecs. This automatically handles required/optional properties and generates a corresponding JSON Schema.

    Note: To make a property optional in an interface, wrap its codec in optional().

  9. Transform Tuple values with mapping functions

    master

    Tuples provide several methods to transform their contents without mutating the original instance:

    • mapFirst(f): Applies function f to the first element, returning a new Tuple<F2, S>.
    • map(f): Applies function f to the second element, returning a new Tuple<F, S2>.
    • bimap(f, g): Applies f to the first element and g to the second, returning a new Tuple<F2, S2>.
    • swap(): Returns a new tuple with the elements in reverse order.