1.3.1 • Published 5 years ago

@0x2e757/monads v1.3.1

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

Monads

TypeScript monad library, transpiled to ES2015 JavaScript.

Install

npm i @0x2e757/monads

Usage

Library contains two classes - StaticMonad andDynamicMonad, which are implementation of IMonad<T> and IComparable<T> interfaces.

How to import

import { IMonad, StaticMonad, DynamicMonad } from "@0x2e757/monads";

IMonad interface

export interface IMonad<T> {
    set: (value: T) => void;
    setter: (value: T) => () => void;
    toggle: () => void;
    emit: () => T;
    subscribe: (callback: Subscriber<T>, triggerImmediately?: boolean) => void;
    unsubscribe: (callback: Subscriber<T>) => void;
    applyMiddleware: (middleware: Middleware<T>) => void;
    dispose: () => void;
}

* Methods set, setter, toggle and applyMiddleware are available only on StaticMonad instances. Calling them from DynamicMonad instance results in exception.

IComparable interface

export interface IComparable<T> {
    seq: (value: T) => boolean;  // Strict equality check
    sneq: (value: T) => boolean; // Strict inequality check
    eq: (value: T) => boolean;  // Equality check
    neq: (value: T) => boolean; // Inequality check
    lt: (value: T) => boolean;  // Check value less than
    lte: (value: T) => boolean; // Check value less than or equal to
    gt: (value: T) => boolean;  // Check value greater than
    gte: (value: T) => boolean; // Check value greater than or equal to
}

StaticMonad

Simple monad that can be used as a value container with assignable on update callbacks.

Usage example:

let mSomeValue = new StaticMonad(0);
mSomeValue.subscribe(console.log);
mSomeValue.set(1);
mSomeValue.applyMiddleware((next) => (value) => {
    next(value > 5 ? 5 : value);
});
mSomeValue.set(10);
let someValue = mSomeValue.emit();

DynamicMonad

Advanced monad which contains dynamically computed value (it can not be set manually).

Usage example:

let mUsername = new StaticMonad("John");
let mBalance = new StaticMonad(100);
let mBankAccountInfo = new DynamicMonad(mUsername, mBalance, (username, balance) => `${username} has ${balance}$.`);
mBankAccountInfo.subscribe(console.log, true);
mBalance.set(mBalance.emit() - 50);
// Console output:
// > John has 100$.
// > John has 50$.
1.4.0

5 years ago

1.3.1

5 years ago

1.3.0

5 years ago

1.2.0

5 years ago

1.1.0

5 years ago

1.2.1

5 years ago

1.0.1

5 years ago

1.0.0

5 years ago