purify-ts
repository·master·Indexed 23 days ago
https://github.com/gigobyte/purifyA 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.
What's inside purify-ts
- Purify is a functional programming library for TypeScript. It provides popular functional patterns and abstractions designed to be developer-friendly and type-safe. It is also Fantasy Land conformant.
Install the gatsby-starter-default
masterTo use this starter, you must first have the Gatsby CLI installed globally. You can then create a new site using the
gatsby newcommand.npm install --global gatsby-cli gatsby new gatsby-example-siteInstall purify-ts via npm or yarn
masterPurify 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-tsRun the gatsby-starter-default development server
masterAfter creating your site, navigate into the project directory and use
npm run developto start the local development server.cd gatsby-example-site npm run developUse the Maybe type for optional values
masterThe
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 typeT.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, andorDefaultto transform or recover values safely.Use the Either type for error handling
masterThe
Either<L, R>type represents a value that can be one of two types:Left(conventionally used for errors or failures) orRight(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 theRightvalue if present.mapLeft(f): Transforms theLeftvalue if present.bimap(f, g): Transforms bothLeftandRightvalues using different functions.chain(f): Chains computations that return anotherEither(monadic bind).caseOf(patterns): Performs structural pattern matching.
To create an
Either, use theLeftandRightconstructors.How MaybeAsync works and handles failures
masterMaybeAsync<T>is a type that represents an asynchronous computation resulting in aMaybe<T>. It extendsPromiseLike<Maybe<T>>.Failure Semantics: When calling
.run(), the resultingPromise<Maybe<T>>will resolve toNothingin the following cases:- Any computation inside the
MaybeAsyncresolves toNothing. - Any of the internal promises are rejected.
- An exception is thrown during execution.
If no failures occur, it returns a promise resolved to a
Justcontaining the value.Key Methods for Control Flow:
run(): Executes the computation and returnsPromise<Maybe<T>>.map<U>(f: (value: T) => U): Transforms the value if it is aJust. IfNothing, the mapping function is skipped and the result isNothing.chain<U>(f: (value: T) => PromiseLike<Maybe<U>>): Chains another asynchronousMaybeoperation. Similar toMaybe#chainbut handles promises.orDefault(defaultValue: T): Returns thedefaultValueif the result isNothing, otherwise returns the unwrapped value.filter<U extends T>(pred: (value: T) => value is U | (value: T) => boolean): Returnsthisif the predicate passes, otherwise returnsNothing.
- Any computation inside the
Combine codecs with oneOf, nullable, and optional
masterPurify 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 ornull.optional<T>(codec): A codec that accepts either the provided codec orundefined. This is specifically designed for use withinCodec.interfaceto mark properties as optional.intersect(codecA, codecB): Creates an intersection. For objects, it merges the results of both codecs.
Perform predicate tests on Tuples
masterYou can test the contents of a tuple using
everyandsome:every(pred): Returnstrueif the predicatepredreturnstruefor both elements.some(pred): Returnstrueif the predicatepredreturnstruefor at least one element.
Use fanout to construct tuples from a single value
masterThe
fanoutmethod allows you to derive a tuple from a single input value using two different transformation functions. It supports three different usage patterns:- Immediate execution: Pass two functions and a value to get a
Tupleimmediately. - Function composition: Pass two functions to get a new function that accepts a value and returns a
Tuple. - Curried composition: Pass one function to get a higher-order function for building complex pipelines.
- Immediate execution: Pass two functions and a value to get a
Create an object codec with Codec.interface
masterUse
Codec.interfaceto 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().Transform Tuple values with mapping functions
masterTuples provide several methods to transform their contents without mutating the original instance:
mapFirst(f): Applies functionfto the first element, returning a newTuple<F2, S>.map(f): Applies functionfto the second element, returning a newTuple<F, S2>.bimap(f, g): Appliesfto the first element andgto the second, returning a newTuple<F2, S2>.swap(): Returns a new tuple with the elements in reverse order.