0.0.7 • Published 6 years ago

zanpakuto v0.0.7

Weekly downloads
3
License
MIT
Repository
github
Last release
6 years ago

zanpakuto

GitHub license npm version Build Status Coverage Status

$ yarn add zanpakuto

compose

It's like Object.assign(), but even more.

import { compose } from 'zanpakuto';
...
compose({})
    .if(hasFoo && hasBar, {
        foo: 'Foo',
        bar: 'Bar'
    }).elseif(hasFoo, {
        foo: 'Foo'
    }).elseif(hasBar, {
        bar: 'Bar'
    }).else({
        noFooNoBar: 'NoFooNoBar'
    }).val();
hasFoo \ hasBartruefalse
true{ foo: 'Foo', bar: 'Bar' }{ foo: 'Foo' }
false{ bar: 'Bar' }{ noFooNoBar: 'NoFooNoBar' }

Example

Suppose you compose an HTTP request to upload a file. You decide to set content type based on a file extension and apply gzip for javascript and css files.

import { compose } from 'zanpakuto';
...
const createRequest = (payload: any, fileExt: string) => 
    compose({
        body: { ...payload }
    }).if(fileExt === '.js', {
        contentType: 'text/javascript'
    }).elseif(fileExt === '.css', {
        contentType: 'text/css'
    }).else({
        contentType: 'application/octet-stream'
    }).if(fileExt === '.js' || fileExt === '.css', {
        encoding: 'gzip'
    }).val();

API

methoddescription
compose\<A extends {}>(a: A = {} as any): IComposer\Creates a wrapper around a given object a: A that is a context object.
append\(b: B): IComposer\<A | B>Appends a given object b to the context A
if\(condition: boolean, b: B): IComposer\<A | B>Appends a given object b to the context A if and only if the condition is satisfied.
elseif\(condition: boolean, c: C): IComposer\<A | C>Appends a given object c to the context A if and only if the condition is satisfied and a previous conditions were falsy.
else\(d: D): IComposer\<A | D>Appends a given object d to the context A if all previous conditions were falsy.
val(): ASimply returns the context object A.
export interface IComposer<A> {

    append<B>(b: B): IComposer<A | B>;

    if<B>(condition: boolean, b: B): IComposer<A | B>;

    elseif<C>(condition: boolean, c: C): IComposer<A | C>

    else<D>(d: D): IComposer<A | D>;

    val(): A;
}

License

MIT