zso
TypeScript icon, indicating that this package has built-in type declarations

0.5.8 • Public • Published

Zso

NPM version Test coverage Size License

$

jQuery like style dom manipulator.

Type Definition
namespace $ {
    class $ extends Select {
        find(selector: string): $;
        each(fn: types.AnyFn): $;
        offset(): $offset.IOffset;
        hide(): $;
        show(): $;
        first(): $;
        last(): $;
        get(index: number): Element;
        eq(index: number): $;
        on(event: string, selector: string, handler: types.AnyFn): $;
        on(event: string, handler: types.AnyFn): $;
        off(event: string, selector: string, handler: types.AnyFn): $;
        off(event: string, handler: types.AnyFn): $;
        html(): string;
        html(value: string): $;
        text(): string;
        text(value: string): $;
        val(): string;
        val(value: string): $;
        css(name: string): string;
        css(name: string, value: string): $;
        css(properties: types.PlainObj<string | number>): $;
        attr(name: string): string;
        attr(name: string, value: string): $;
        attr(attributes: types.PlainObj<string>): $;
        data(name: string): string;
        data(name: string, value: string): $;
        data(attributes: types.PlainObj<string>): $;
        rmAttr(name: string): $;
        remove(): $;
        addClass(name: string | string[]): $;
        rmClass(name: string): $;
        toggleClass(name: string): $;
        hasClass(name: string): boolean;
        parent(): $;
        append(content: string | Element): $;
        prepend(content: string | Element): $;
        before(content: string | Element): $;
        after(content: string | Element): $;
    }
}
declare function $(selector: string | Element | Document): $.$;

Available methods

offset, hide, show, first, last, get, eq, on, off, html, text, val, css, attr, data, rmAttr, remove, addClass, rmClass, toggleClass, hasClass, append, prepend, before, after

const $btn = $('#btn');
$btn.html('eustia');
$btn.addClass('btn');
$btn.show();
$btn.on('click', function() {
    // Do something...
});

$attr

Element attribute manipulation.

Type Definition
namespace $attr {
    function remove(element: $safeEls.El, name: string): void;
}
function $attr(
    element: $safeEls.El,
    name: string,
    value: string
): void;
function $attr(
    element: $safeEls.El,
    attributes: types.PlainObj<string>
): void;
function $attr(element: $safeEls.El, name: string): string;

Get the value of an attribute for the first element in the set of matched elements.

Name Desc
element Elements to manipulate
name Attribute name
return Attribute value of first element

Set one or more attributes for the set of matched elements.

Name Desc
element Elements to manipulate
name Attribute name
val Attribute value
Name Desc
element Elements to manipulate
attributes Object of attribute-value pairs to set

remove

Remove an attribute from each element in the set of matched elements.

Name Desc
element Elements to manipulate
name Attribute name
$attr('#test', 'attr1', 'test');
$attr('#test', 'attr1'); // -> test
$attr.remove('#test', 'attr1');
$attr('#test', {
    attr1: 'test',
    attr2: 'test'
});

$class

Element class manipulations.

Type Definition
const $class: {
    add(element: $safeEls.El, name: string | string[]): void;
    has(element: $safeEls.El, name: string): boolean;
    toggle(element: $safeEls.El, name: string): void;
    remove(element: $safeEls.El, name: string): void;
};

add

Add the specified class(es) to each element in the set of matched elements.

Name Desc
element Elements to manipulate
names Classes to add

has

Determine whether any of the matched elements are assigned the given class.

Name Desc
element Elements to manipulate
name Class name
return True if elements has given class name

toggle

Add or remove one or more classes from each element in the set of matched elements, depending on either the class's presence or the value of the state argument.

Name Desc
element Elements to manipulate
name Class name to toggle

remove

Remove a single class, multiple classes, or all classes from each element in the set of matched elements.

Name Desc
element Elements to manipulate
name Class names to remove
$class.add('#test', 'class1');
$class.add('#test', ['class1', 'class2']);
$class.has('#test', 'class1'); // -> true
$class.remove('#test', 'class1');
$class.has('#test', 'class1'); // -> false
$class.toggle('#test', 'class1');
$class.has('#test', 'class1'); // -> true

$css

Element css manipulation.

Type Definition
function $css(element: $safeEls.El, name: string): string;
function $css(
    element: $safeEls.El,
    name: string,
    val: string
): void;
function $css(
    element: $safeEls.El,
    properties: types.PlainObj<string | number>
): void;

Get the computed style properties for the first element in the set of matched elements.

Name Desc
element Elements to manipulate
name Property name
return Css value of first element

Set one or more CSS properties for the set of matched elements.

Name Desc
element Elements to manipulate
name Property name
val Css value
Name Desc
element Elements to manipulate
properties Object of css-value pairs to set
$css('#test', {
    color: '#fff',
    background: 'black',
    opacity: 0.5
});
$css('#test', 'display', 'block');
$css('#test', 'color'); // -> #fff

$data

Wrapper of $attr, adds data- prefix to keys.

Type Definition
function $data(
    element: $safeEls.El,
    name: string,
    value: string
): void;
function $data(
    element: $safeEls.El,
    attributes: types.PlainObj<string>
): void;
function $data(element: $safeEls.El, name: string): string;
$data('#test', 'attr1', 'eustia');

$event

bind events to certain dom elements.

Type Definition
const $event: {
    on(
        element: $safeEls.El,
        event: string,
        selector: string,
        handler: types.AnyFn
    ): void;
    on(element: $safeEls.El, event: string, handler: types.AnyFn): void;
    off(
        element: $safeEls.El,
        event: string,
        selector: string,
        handler: types.AnyFn
    ): void;
    off(element: $safeEls.El, event: string, handler: types.AnyFn): void;
};
function clickHandler() {
    // Do something...
}
$event.on('#test', 'click', clickHandler);
$event.off('#test', 'click', clickHandler);

$insert

Insert html on different position.

Type Definition
namespace $insert {
    type IInsert = (element: $safeEls.El, content: string | Element) => void;
}
const $insert: {
    before: $insert.IInsert;
    after: $insert.IInsert;
    append: $insert.IInsert;
    prepend: $insert.IInsert;
};

before

Insert content before elements.

after

Insert content after elements.

prepend

Insert content to the beginning of elements.

append

Insert content to the end of elements.

Name Desc
element Elements to manipulate
content Html strings or element
// <div id="test"><div class="mark"></div></div>
$insert.before('#test', '<div>zso</div>');
// -> <div>zso</div><div id="test"><div class="mark"></div></div>
$insert.after('#test', '<div>zso</div>');
// -> <div id="test"><div class="mark"></div></div><div>zso</div>
$insert.prepend('#test', '<div>zso</div>');
// -> <div id="test"><div>zso</div><div class="mark"></div></div>
$insert.append('#test', '<div>zso</div>');
// -> <div id="test"><div class="mark"></div><div>zso</div></div>

$offset

Get the position of the element in document.

Type Definition
namespace $offset {
    interface IOffset {
        left: number;
        top: number;
        width: number;
        height: number;
    }
}
function $offset(element: $safeEls.El): $offset.IOffset;
Name Desc
element Elements to get offset
return Element position
$offset('#test'); // -> {left: 0, top: 0, width: 0, height: 0}

$property

Element property html, text, val getter and setter.

Type Definition
namespace $property {
    interface IProperty {
        (element: $safeEls.El, value: string): void;
        (element: $safeEls.El): string;
    }
}
const $property: {
    html: $property.IProperty;
    val: $property.IProperty;
    text: $property.IProperty;
};

html

Get the HTML contents of the first element in the set of matched elements or set the HTML contents of every matched element.

text

Get the combined text contents of each element in the set of matched elements, including their descendants, or set the text contents of the matched elements.

val

Get the current value of the first element in the set of matched elements or set the value of every matched element.

$property.html('#test', 'zso');
$property.html('#test'); // -> zso

$remove

Remove the set of matched elements from the DOM.

Type Definition
function $remove(element: $safeEls.El);
Name Desc
element Elements to delete
$remove('#test');

$safeEls

Convert value into an array, if it's a string, do querySelector.

Type Definition
namespace $safeEls {
    type El = Element | Element[] | NodeListOf<Element> | string;
}
function $safeEls(val: $safeEls.El): Element[];
Name Desc
val Value to convert
return Array of elements
$safeEls(document.querySelector('.test'));
$safeEls(document.querySelectorAll('.test'));
$safeEls('.test'); // -> Array of elements with test class

$show

Show elements.

Type Definition
function $show(element: $safeEls.El): void;
Name Desc
element Elements to show
$show('#test');

Benchmark

JavaScript Benchmark.

Type Definition
namespace Benchmark {
    interface IOptions {
        minTime?: number;
        maxTime?: number;
        minSamples?: number;
        delay?: number;
        name?: string;
    }
    interface IResult {
        name: string;
        mean: number;
        variance: number;
        deviation: number;
        sem: number;
        moe: number;
        rme: number;
        hz: number;
        sample: number[];
    }
}
class Benchmark {
    constructor(fn: types.AnyFn, options?: Benchmark.IOptions);
    run(): Promise<Benchmark.IResult>;
    static all(
        benches: Array<types.AnyFn | Benchmark>,
        options?: Benchmark.IOptions
    ): Promise<Benchmark.IResult[]>;
}

constructor

Name Desc
fn Code for speed testing
options Benchmark options

Available options:

Name Desc
minTime=50 Time needed to reduce uncertainty
maxTime=5000 Maximum time for running benchmark
minSamples=5 Minimum sample size
delay=5 Delay between test cycles
name Benchmark name

run

Run benchmark, returns a promise.

all

[static] Run some benchmarks.

const benchmark = new Benchmark(
    function test() {
        !!'Hello World!'.match(/o/);
    },
    {
        maxTime: 1500
    }
);
benchmark.run().then(result => {
    console.log(String(result));
});
Benchmark.all([
    function regExp() {
        /o/.test('Hello World!');
    },
    function indexOf() {
        'Hello World!'.indexOf('o') > -1;
    },
    function match() {
        !!'Hello World!'.match(/o/);
    }
]).then(results => {
    console.log(String(results));
});

Blob

Use Blob when available, otherwise BlobBuilder.

constructor

Name Desc
parts Blob parts
options Options
const blob = new Blob([]);

BloomFilter

Bloom filter implementation.

Type Definition
class BloomFilter {
    constructor(size?: number, k?: number);
    add(val: string): void;
    test(val: string): boolean;
}

constructor

Name Desc
size=1024 Number of buckets
k=3 Number of Hash functions

add

Add an element to the filter.

Name Desc
val Value to add

test

Test if an element is in the filter.

Name Desc
val Value to test
return True if probably, false if definitely not
const bloom = new BloomFilter(256, 3);
bloom.add('Bruce Wayne');
bloom.add('Clark Kent');
bloom.test('Clark Kent'); // -> true
bloom.test('Bruce Wayne'); // -> true
bloom.test('Tony Stark'); // -> false

Caseless

Modify object props without caring about letter case.

Type Definition
class Caseless {
    constructor(obj: any);
    getKey(key: string): string | void;
    set(key: string, val: any): void;
    get(key: string): any;
    remove(key: string): void;
    has(key: string): boolean;
}

constructor

Name Desc
obj Target object

getKey

Get key with preserved casing.

Name Desc
key Caseless key
return Object key

set

Set value.

Name Desc
key Caseless key
val Value to set

get

Get value.

Name Desc
key Caseless key
return Value of given key

remove

Remove value.

Name Desc
key Caseless key

has

Determine whether target object has given key.

Name Desc
key Caseless key
return True if has given key
const headers = { 'Content-Type': 'text/javascript' };
const c = new Caseless(headers);
c.set('content-type', 'text/css');
console.log(headers); // -> { 'Content-Type': 'text/css' }
c.getKey('content-type'); // -> 'Content-Type'
c.remove('content-type');
c.has('content-type'); // -> false

Class

Create JavaScript class.

Type Definition
namespace Class {
    class Base {
        toString(): string;
    }
    class IConstructor extends Base {
        constructor(...args: any[]);
        static extend(methods: any, statics: any): IConstructor;
        static inherits(Class: types.AnyFn): void;
        static methods(methods: any): IConstructor;
        static statics(statics: any): IConstructor;
        [method: string]: any;
    }
}
function Class(methods: any, statics?: any): Class.IConstructor;
Name Desc
methods Public methods
[statics Static methods
return Function used to create instances
const People = Class({
    initialize: function People(name, age) {
        this.name = name;
        this.age = age;
    },
    introduce: function() {
        return 'I am ' + this.name + ', ' + this.age + ' years old.';
    }
});

const Student = People.extend(
    {
        initialize: function Student(name, age, school) {
            this.callSuper(People, 'initialize', arguments);

            this.school = school;
        },
        introduce: function() {
            return (
                this.callSuper(People, 'introduce') +
                '\n I study at ' +
                this.school +
                '.'
            );
        }
    },
    {
        is: function(obj) {
            return obj instanceof Student;
        }
    }
);

const a = new Student('allen', 17, 'Hogwarts');
a.introduce(); // -> 'I am allen, 17 years old. \n I study at Hogwarts.'
Student.is(a); // -> true

Color

Color converter.

Type Definition
namespace Color {
    interface IColor {
        val: number[];
        model: string;
    }
}
class Color {
    constructor(color: string | Color.IColor);
    toRgb(): string;
    toHex(): string;
    toHsl(): string;
    static parse(colorStr: string): Color.IColor;
}

constructor

Name Desc
color Color to convert

toRgb

Get color rgb string format.

toHex

Get color hex string format.

toHsl

Get color hsl string format.

parse

[static] Parse color string into object containing value and model.

Name Desc
color Color string
return Object containing value and model
Color.parse('rgb(170, 287, 204, 0.5)'); // -> {val: [170, 187, 204, 0.5], model: 'rgb'}
const color = new Color('#abc');
color.toRgb(); // -> 'rgb(170, 187, 204)'
color.toHsl(); // -> 'hsl(210, 25%, 73%)'

Delegator

Object delegation.

Type Definition
class Delegator {
    constructor(host: object, target: object | string);
    method(name: string, target?: string): Delegator;
    getter(name: string, target?: string): Delegator;
    setter(name: string, target?: string): Delegator;
    access(name: string, target?: string): Delegator;
}

constructor

Name Desc
host Host object
target Delegation target

method

Allow method to be accessed on the host object.

Name Desc
name Host method name
target=name Target method name

getter

Create a getter.

setter

Create a setter.

access

Create a accessor, same as calling both setter and getter.

const host = {
    target: {
        a() {
            return 'a';
        },
        b: 'b',
        c: 'c',
        d: 'd',
        e() {
            return 'e';
        }
    }
};
const delegator = new Delegator(host, 'target');
delegator
    .method('a')
    .getter('b')
    .setter('c')
    .access('d');
host.a(); // -> 'a'
host.b; // -> 'b'
host.c = 5;
host.target.c; // -> 5
host.d; // -> 'd'
host.d = 5;
host.d; // -> 5

Dispatcher

Flux dispatcher.

Type Definition
class Dispatcher {
    dispatch(payload: any);
    register(cb: types.AnyFn): void;
    waitFor(ids: string[]): void;
    unregister(id: string): void;
    isDispatching(): boolean;
}

Related docs

const dispatcher = new Dispatcher();

dispatcher.register(function(payload) {
    switch (
        payload.actionType
        // Do something
    ) {
    }
});

dispatcher.dispatch({
    actionType: 'action'
});

Emitter

Event emitter class which provides observer pattern.

Type Definition
class Emitter {
    on(event: string, listener: types.AnyFn): Emitter;
    off(event: string, listener: types.AnyFn): Emitter;
    once(event: string, listener: types.AnyFn): Emitter;
    emit(event: string, ...args: any[]): Emitter;
    removeAllListeners(event?: string): Emitter;
    static mixin(obj: any): any;
}

on

Bind event.

off

Unbind event.

once

Bind event that trigger once.

Name Desc
event Event name
listener Event listener

emit

Emit event.

Name Desc
event Event name
...args Arguments passed to listener

removeAllListeners

Remove all listeners.

Name Desc
event Event name

mixin

[static] Mixin object class methods.

Name Desc
obj Object to mixin
const event = new Emitter();
event.on('test', function(name) {
    console.log(name);
});
event.emit('test', 'zso'); // Logs out 'zso'.
Emitter.mixin({});

Enum

Enum type implementation.

Type Definition
class Enum {
    size: number;
    constructor(map: string[] | { [member: string]: any });
    [key: string]: any;
}

constructor

Name Desc
arr Array of strings
Name Desc
obj Pairs of key and value
const importance = new Enum([
    'NONE',
    'TRIVIAL',
    'REGULAR',
    'IMPORTANT',
    'CRITICAL'
]);
const val = 1;
if (val === importance.CRITICAL) {
    // Do something.
}

FileBlobStore

Binary file storage.

Type Definition
class FileBlobStore extends Emitter {
    constructor(path: string, data?: types.PlainObj<Buffer>);
    set(key: string, buf: Buffer): void;
    set(values: types.PlainObj<Buffer>): void;
    get(key: string): Buffer | void;
    get(keys: string[]): types.PlainObj<Buffer>;
    remove(key: string): void;
    remove(keys: string[]): void;
    clear(): void;
    each(fn: (val: Buffer, key: string) => void): void;
    save(): void;
}

Most api is the same as Store module, except only buffer is accepted.

save

Save data to disk.

const store = new FileBlobStore('path/to/file');
store.set('name', Buffer.from('zso'));
process.on('exit', () => store.save());

FileStore

File storage.

Type Definition
class FileStore extends Store {
    constructor(path: string, data?: any);
}

constructor

Name Desc
path File path to store
data Default data
const store = new FileStore('path/to/file');
store.set('name', 'zso');

HashTable

Hash table implementation.

Type Definition
class HashTable {
    constructor(size?: number);
    set(key: string, val: any): void;
    get(key: string): any;
    has(key: string): boolean;
    delete(key: string): void;
}

constructor

Name Desc
size=32 Bucket size

set

Set value.

Name Desc
key Value key
val Value to set

get

Get value.

Name Desc
key Value key
return Value of given key

has

Check if has value.

Name Desc
key Value key
return True if value exists

delete

Delete value.

const hashTable = new HashTable(128);
hashTable.set('name', 'ooo9');
hashTable.get('name'); // -> 'ooo9'
hashTable.has('name'); // -> true
hashTable.delete('name');
hashTable.has('name'); // -> false

Heap

Heap implementation.

Type Definition
class Heap {
    size: number;
    constructor(cmp?: types.AnyFn);
    clear(): void;
    add(item: any): number;
    poll(): any;
    peek(): any;
}

size

Heap size.

constructor

Name Desc
cmp Comparator

clear

Clear the heap.

add

Add an item to the heap.

Name Desc
item Item to add
return Current size

poll

Retrieve and remove the root item of the heap.

peek

Same as poll, but does not remove the item.

const heap = new Heap(function(a, b) {
    return b - a;
});
heap.add(2);
heap.add(1);
heap.add(4);
heap.add(5);
heap.poll(); // -> 5
console.log(heap.size); // -> 4

HeapSnapshot

V8 heap snapshot manipulator.

Type Definition
class HeapSnapshot {
    nodes: LinkedList;
    edges: LinkedList;
    constructor(profile: any);
}

constructor

Name Desc
profile Profile to parse

nodes

Parsed nodes.

edges

Parsed edges.

const fs = require('fs');
const data = fs.readFileSync('path/to/heapsnapshot', 'utf8');
const heapSnapshot = new HeapSnapshot(data);
let totalSize = 0;
heapSnapshot.nodes.forEach(node => (totalSize += node.selfSize));
console.log(totalSize);

I18n

Simple internationalization library.

Type Definition
class I18n {
    constructor(locale: string, langs: types.PlainObj<any>);
    set(locale: string, lang: types.PlainObj<any>): void;
    t(path: string | string[], data?: types.PlainObj<any>): string;
    locale(locale: string): void;
}

constructor

Name Desc
locale Locale code
langs Language data

set

Add language or append extra keys to existing language.

Name Desc
locale Locale code
lang Language data

locale

Set default locale.

Name Desc
locale Locale code

t

Get translation text.

Name Desc
path Path of translation to get
data Data to pass in
return Translation text
const i18n = new I18n('en', {
    en: {
        welcome: 'Hello, {{name}}!',
        curTime(data) {
            return 'Current time is ' + data.time;
        }
    },
    cn: {
        welcome: '你好,{{name}}!'
    }
});
i18n.set('cn', {
    curTime(data) {
        return '当前时间是 ' + data.time;
    }
});
i18n.t('welcome', { name: 'zso' }); // -> 'Hello, zso!'
i18n.locale('cn');
i18n.t('curTime', { time: '5:47 pm' }); // -> '当前时间是 5:47 pm'

JsonTransformer

Json to json transformer.

Type Definition
class JsonTransformer {
    constructor(data: any);
    set(key: string, val: any): JsonTransformer;
    get(key?: string): any;
    map(from: string, to: string, fn: types.AnyFn): JsonTransformer;
    map(from: string, fn: types.AnyFn): JsonTransformer;
    filter(from: string, to: string, fn: types.AnyFn): JsonTransformer;
    filter(from: string, fn: types.AnyFn): JsonTransformer;
    remove(keys: string | string[]): JsonTransformer;
    compute(
        from: string | string[],
        to: string,
        fn: types.AnyFn
    ): JsonTransformer;
    compute(from: string, fn: types.AnyFn): JsonTransformer;
    toString(): string;
}

constructor

Name Desc
data={} Json object to manipulate

set

Set object value.

Name Desc
key Object key
val Value to set

If key is not given, the whole source object is replaced by val.

get

Get object value.

Name Desc
key Object key
return Specified value or whole object

remove

Remove object value.

Name Desc
key Object keys to remove

map

Shortcut for array map.

Name Desc
from From object path
to Target object path
fn Function invoked per iteration

filter

Shortcut for array filter.

compute

Compute value from several object values.

Name Desc
from Source values
to Target object path
fn Function to compute target value
const data = new JsonTransformer({
    books: [
        {
            title: 'Book 1',
            price: 5
        },
        {
            title: 'Book 2',
            price: 10
        }
    ],
    author: {
        lastname: 'Su',
        firstname: 'RedHood'
    }
});
data.filter('books', function(book) {
    return book.price > 5;
});
data.compute('author', function(author) {
    return author.firstname + author.lastname;
});
data.set('count', data.get('books').length);
data.get(); // -> {books: [{title: 'Book 2', price: 10}], author: 'ooo9', count: 1}

LinkedList

Doubly-linked list implementation.

Type Definition
namespace LinkedList {
    class Node {
        value: any;
        prev: Node | null;
        next: Node | null;
    }
}
class LinkedList {
    size: number;
    head: LinkedList.Node;
    tail: LinkedList.Node;
    push(val: any): number;
    pop(): any;
    unshift(val: any): number;
    shift(): any;
    find(fn: types.AnyFn): LinkedList.Node | void;
    delNode(node: LinkedList.Node): void;
    forEach(iterator: types.AnyFn, ctx?: any);
    toArr(): any[];
}

size

List size.

head.

First node.

tail

Last node.

push

Add an value to the end of the list.

Name Desc
val Value to push
return Current size

pop

Get the last value of the list.

unshift

Add an value to the head of the list.

shift

Get the first value of the list.

rmNode

Remove node.

find

Find node.

Name Desc
fn Function invoked per iteration
return First value that passes predicate

forEach

Iterate over the list.

toArr

Convert the list to a JavaScript array.

const linkedList = new LinkedList();
linkedList.push(5);
linkedList.pop(); // -> 5

LocalStore

LocalStorage wrapper.

Type Definition
class LocalStore extends Store {
    constructor(name: string, data?: {});
}

Extend from Store.

constructor

Name Desc
name LocalStorage item name
data Default data
const store = new LocalStore('zso');
store.set('name', 'zso');

Logger

Simple logger with level filter.

Type Definition
class Logger extends Emitter {
    name: string;
    formatter(type: string, argList: any[]): any[];
    constructor(name: string, level?: string | number);
    setLevel(level: string | number): Logger;
    getLevel(): number;
    trace(...args: any[]): Logger;
    debug(...args: any[]): Logger;
    info(...args: any[]): Logger;
    warn(...args: any[]): Logger;
    error(...args: any[]): Logger;
    static level: Enum;
}

constructor

Name Desc
name Logger name
level=DEBUG Logger level

setLevel

Set level.

Name Desc
level Logger level

getLevel

Get current level.

trace, debug, info, warn, error

Logging methods.

Log Levels

TRACE, DEBUG, INFO, WARN, ERROR and SILENT.

const logger = new Logger('zso', Logger.level.ERROR);
logger.trace('test');

// Format output.
logger.formatter = function(type, argList) {
    argList.push(new Date().getTime());

    return argList;
};

logger.on('all', function(type, argList) {
    // It's not affected by log level.
});

logger.on('debug', function(argList) {
    // Affected by log level.
});

Lru

Simple LRU cache.

Type Definition
class Lru {
    constructor(max: number);
    has(key: string): boolean;
    remove(key: string): void;
    get(key: string): any;
    set(key: string, val: any): void;
    clear(): void;
}

constructor

Name Desc
max Max items in cache

has

Check if has cache.

Name Desc
key Cache key
return True if value exists

remove

Remove cache.

Name Desc
key Cache key

get

Get cache value.

Name Desc
key Cache key
return Cache value

set

Set cache.

Name Desc
key Cache key
val Cache value

clear

Clear cache.

const cache = new Lru(50);
cache.set('test', 'zso');
cache.get('test'); // -> 'zso'

MediaQuery

CSS media query listener.

Type Definition
class MediaQuery extends Emitter {
    constructor(query: string);
    isMatch(): boolean;
}

Extend from Emitter.

constructor

Name Desc
query Media query

isMatch

Return true if given media query matches.

Events

match

Triggered when a media query matches.

unmatch

Opposite of match.

const mediaQuery = new MediaQuery('screen and (max-width:1000px)');
mediaQuery.isMatch(); // -> false
mediaQuery.on('match', () => {
    // Do something...
});

MutationObserver

Safe MutationObserver, does nothing if MutationObserver is not supported.

const observer = new MutationObserver(function(mutations) {
    // Do something.
});
observer.observe(document.documentElement);
observer.disconnect();

PriorityQueue

Priority queue implementation.

Type Definition
class PriorityQueue {
    size: number;
    constructor(cmp?: types.AnyFn);
    clear(): void;
    enqueue(item: any): number;
    dequeue(): any;
    peek(): any;
}

size

Queue size.

constructor

Name Desc
cmp Comparator

clear

Clear the queue.

enqueue

Add an item to the queue.

Name Desc
item Item to add
return Current size

dequeue

Retrieve and remove the highest priority item of the queue.

peek

Same as dequeue, but does not remove the item.

const queue = new PriorityQueue(function(a, b) {
    if (a.priority > b.priority) return 1;
    if (a.priority === b.priority) return -1;
    return 0;
});
queue.enqueue({
    priority: 1000,
    value: 'apple'
});
queue.enqueue({
    priority: 500,
    value: 'orange'
});
queue.dequeue(); // -> { priority: 1000, value: 'apple' }

Promise

Lightweight Promise implementation.

Promises spec

function get(url) {
    return new Promise(function(resolve, reject) {
        const req = new XMLHttpRequest();
        req.open('GET', url);
        req.onload = function() {
            req.status == 200
                ? resolve(req.response)
                : reject(Error(req.statusText));
        };
        req.onerror = function() {
            reject(Error('Network Error'));
        };
        req.send();
    });
}

get('test.json').then(function(result) {
    // Do something...
});

PseudoMap

Like es6 Map, without iterators.

Type Definition
const PseudoMap: typeof Map;

It supports only string keys, and uses Map if exists.

const map = new PseudoMap();
map.set('1', 1);
map.get('1'); // -> 1

Queue

Queue data structure.

Type Definition
class Queue {
    size: number;
    clear(): void;
    enqueue(item: any): number;
    dequeue(): any;
    peek(): any;
    forEach(iterator: types.AnyFn, context?: any): void;
    toArr(): any[];
}

size

Queue size.

clear

Clear the queue.

enqueue

Add an item to the queue.

Name Desc
item Item to enqueue
return Current size

dequeue

Remove the first item of the queue.

peek

Get the first item without removing it.

forEach

Iterate over the queue.

Name Desc
iterator Function invoked iteration
ctx Function context

toArr

Convert queue to a JavaScript array.

const queue = new Queue();

console.log(queue.size); // -> 0
queue.enqueue(2);
queue.enqueue(3);
queue.dequeue(); // -> 2
console.log(queue.size); // -> 1
queue.peek(); // -> 3
console.log(queue.size); // -> 1

QuickLru

LRU implementation without linked list.

Type Definition
class QuickLru {
    constructor(max: number);
    has(key: string): boolean;
    remove(key: string): void;
    get(key: string): any;
    set(key: string, val: any): void;
    clear(): void;
}

Inspired by the hashlru algorithm.

The api is the same as Lru module.

const cache = new QuickLru(50);
cache.set('test', 'zso');
cache.get('test'); // -> 'zso'

Readiness

Readiness manager.

Type Definition
class Readiness {
    signal(tasks: string | string[]): void;
    isReady(tasks: string | string[]): boolean;
    ready(tasks: string | string[], fn?: types.AnyFn): Promise<void>;
}

signal

Signal task is ready.

Name Desc
tasks Ready tasks

ready

Register ready callback.

Name Desc
tasks Tasks to listen
fn Callback to trigger if tasks are ready
return Promise that will be resolved when ready

isReady

Check if tasks are ready.

Name Desc
tasks Tasks to check
return True if all tasks are ready
const readiness = new Readiness();
readiness.ready('serverCreated', function() {
    // Do something.
});
readiness.signal('serverCreated');
readiness.isReady('serverCreated'); // -> true

ReduceStore

Simplified redux like state container.

Type Definition
class ReduceStore {
    constructor(reducer: types.AnyFn, initialState: any);
    subscribe(listener: types.AnyFn): types.AnyFn;
    dispatch(action: any): any;
    getState(): any;
}

constructor

Name Desc
reducer Function returns next state
initialState Initial state

subscribe

Add a change listener.

Name Desc
listener Callback to invoke on every dispatch
return Function to unsubscribe

dispatch

Dispatch an action.

Name Desc
action Object representing changes
return Same action object

getState

Get the current state.

const store = new ReduceStore(function(state, action) {
    switch (action.type) {
        case 'INCREMENT':
            return state + 1;
        case 'DECREMENT':
            return state - 1;
        default:
            return state;
    }
}, 0);

store.subscribe(function() {
    console.log(store.getState());
});

store.dispatch({ type: 'INCREMENT' }); // 1
store.dispatch({ type: 'INCREMENT' }); // 2
store.dispatch({ type: 'DECREMENT' }); // 1

ResizeSensor

Detect if element's size has changed.

Type Definition
class ResizeSensor extends SingleEmitter {
    constructor(el: HTMLElement);
    destroy(): void;
}

constructor

Name Desc
element Element to monitor size

destroy

Stop monitoring resize event.

const target = document.getElementById('test');
const sensor = new ResizeSensor(target);
sensor.addListener(function() {
    // Trigger if element's size changed.
});

Select

Simple wrapper of querySelectorAll to make dom selection easier.

Type Definition
class Select {
    constructor(selector: string | Element | Document);
    find(selector: string): Select;
    each(fn: types.AnyFn): Select;
}

constructor

Name Desc
selector Dom selector string

find

Get desdendants of current matched elements.

Name Desc
selector Dom selector string

each

Iterate over matched elements.

Name Desc
fn Function to execute for each element
const $test = new Select('#test');
$test.find('.test').each(function(idx, element) {
    // Manipulate dom nodes
});

Semaphore

Limit simultaneous access to a resource.

Type Definition
class Semaphore {
    constructor(counter?: number);
    wait(fn: () => void): void;
    signal(): void;
}

constructor

Name Desc
counter=1 Initial counter

wait

Wait to execute until counter is bigger than 0.

Name Desc
fn Function to execute

signal

Wake up one waiter if any.

const sem = new Semaphore(10);
require('http')
    .createServer((req, res) => {
        sem.wait(function() {
            res.end('.');
            setTimeout(() => sem.signal(), 500);
        });
    })
    .listen(3000);

SessionStore

SessionStorage wrapper.

Type Definition
class SessionStore extends Store {
    constructor(name: string, data?: any);
}

Extend from Store.

constructor

Name Desc
name SessionStorage item name
data Default data
const store = new SessionStore('zso');
store.set('name', 'zso');

SingleEmitter

Event emitter with single event type.

Type Definition
class SingleEmitter {
    addListener(listener: types.AnyFn): void;
    rmListener(listener: types.AnyFn): void;
    emit(...args: any[]): void;
    rmAllListeners(): void;
    static mixin(obj: any): void;
}

addListener

Add listener.

rmListener

Remove listener.

Name Desc
listener Event listener

rmAllListeners

Remove all listeners.

emit

Call listeners.

Name Desc
...args Arguments passed to listener

mixin

[static] Mixin object class methods.

Name Desc
obj Object to mixin
const event = new SingleEmitter();
event.addListener(function(name) {
    console.log(name);
});
event.emit('zso'); // Logs out 'zso'.

Socket

Tiny WebSocket wrapper.

Type Definition
class Socket extends Emitter {
    constructor(
        url: string,
        options?: {
            protocols?: string | string[];
            reconnect?: boolean;
        }
    );
    send(message: any): void;
    close(code?: number, reason?: string): void;
    connect(): void;
}

Extend from Emitter.

constructor

Name Desc
url Url to connect
options Connect options

Available options:

Name Desc
protocols Protocol string
reconnect=true Try to reconnect if possible

send

Send message.

Name Desc
message Message to send

close

Close WebSocket.

Name Desc
code Status code
reason Reason of closing

connect

Connect WebSocket, called when initialized.

const ws = new Socket('ws://localhost:8001');
ws.on('open', e => ws.send('Hello'));

Stack

Stack data structure.

Type Definition
class Stack {
    size: number;
    clear(): void;
    push(item: any): number;
    pop(): any;
    peek(): any;
    forEach(iterator: types.AnyFn, context?: any): void;
    toArr(): any[];
}

size

Stack size.

clear

Clear the stack.

push

Add an item to the stack.

Name Desc
item Item to add
return Current size

pop

Get the last item of the stack.

peek

Get the last item without removing it.

forEach

Iterate over the stack.

Name Desc
iterator Function invoked iteration
ctx Function context

toArr

Convert the stack to a JavaScript array.

const stack = new Stack();

stack.push(2); // -> 1
stack.push(3); // -> 2
stack.pop(); // -> 3

State

Simple state machine.

Type Definition
class State extends Emitter {
    constructor(initial: string, events: any);
    is(state: string): boolean;
    [event: string]: any;
}

Extend from Emitter.

constructor

Name Desc
initial Initial state
events Events to change state

is

Check current state.

Name Desc
state State to check
return True if current state equals given value
const state = new State('empty', {
    load: { from: 'empty', to: 'pause' },
    play: { from: 'pause', to: 'play' },
    pause: { from: ['play', 'empty'], to: 'pause' },
    unload: { from: ['play', 'pause'], to: 'empty' }
});

state.is('empty'); // -> true
state.load();
state.is('pause'); // -> true
state.on('play', function(src) {
    console.log(src); // -> 'eustia'
});
state.on('error', function(err, event) {
    // Error handler
});
state.play('eustia');

Store

Memory storage.

Type Definition
class Store extends Emitter {
    constructor(data?: {});
    set(key: string, val: any): void;
    set(values: {}): void;
    get(key: string): any;
    get(keys: string[]): {};
    remove(key: string): void;
    remove(keys: string[]): void;
    clear(): void;
    each(fn: (...args: any[]) => void): void;
}

Extend from Emitter.

constructor

Name Desc
data Initial data

set

Set value.

Name Desc
key Value key
val Value to set

Set values.

Name Desc
values Key value pairs

This emit a change event whenever is called.

get

Get value.

Name Desc
key Value key
return Value of given key

Get values.

Name Desc
keys Array of keys
return Key value pairs

remove

Remove value.

Name Desc
key Key to remove

clear

Clear all data.

each

Iterate over values.

Name Desc
fn Function invoked per iteration
const store = new Store('test');
store.set('user', { name: 'zso' });
store.get('user').name; // -> 'zso'
store.clear();
store.each(function(val, key) {
    // Do something.
});
store.on('change', function(key, newVal, oldVal) {
    // It triggers whenever set is called.
});

Trace

Parse, manipulate and generate chrome tracing data.

Type Definition
namespace Trace {
    interface IEvent {
        name: string;
        cat: string;
        ph: string;
        ts: number;
        pid: number;
        tid: number;
        args: any;
        [key: string]: any;
    }
    class Process {
        constructor(id);
        id(): string;
        name(): string;
        addEvent(IEvent): void;
        rmEvent(IEvent): void;
        getThread(id: number): Thread;
        rmThread(id: number): void;
        threads(): Thread[];
        toJSON(): IEvent[];
    }
    class Thread {
        constructor(id, pid);
        id(): string;
        name(): string;
        addEvent(IEvent): void;
        rmEvent(IEvent): void;
        events(): IEvent[];
        toJSON(): IEvent[];
    }
}
class Trace {
    constructor(events: Trace.IEvent[]);
    addEvent(event: Trace.IEvent);
    rmEvent(event: Trace.IEvent);
    getProcess(id: number): Trace.Process;
    rmProcess(id: number): void;
    processes(): Trace.Process[];
    toJSON(): Trace.IEvent[];
}
const fs = require('fs');
const data = fs.readFileSync('path/to/trace', 'utf8');
const trace = new Trace(JSON.parse(data));
trace.rmProcess(627);
fs.writeFileSync(
    'path/to/trace',
    JSON.stringify(trace.toJSON()),
    'utf8',
    function() {}
);

Tracing

Easily create chrome tracing data.

Type Definition
class Tracing {
    constructor(options?: {
        pid?: number;
        tid?: number;
        processName?: string;
        threadName?: string;
    });
    start(cat?: string): void;
    stop(): Trace.IEvent[];
    metadata(name: string, args: any): void;
    begin(cat: string, name: string, args?: any): void;
    end(args?: any): void;
    asyncBegin(cat: string, name: string, id?: string, args?: any): string;
    asyncEnd(id: string, args?: any): void;
    instant(
        cat: string,
        name: string,
        scope?: 'g' | 'p' | 't',
        args?: any
    ): void;
    id(): string;
}

constructor

Name Desc
options Tracing options

Available options:

Name Desc
pid Process id
tid Thread id
processName Process name
threadName Thread name

start

Start recording.

Name Desc
cat Enabled categories

stop

Stop recording and get result events.

begin

Record begin event.

Name Desc
cat Event categories
name Event name
args Arguments

end

Record end event.

asyncBegin

Record async begin event.

asyncEnd

Record async end event.

instant

Record instant event.

id

Get an unique id.

const fs = require('fs');
const tracing = new Tracing();
tracing.start();
tracing.begin('cat', 'name');
// Do something...
tracing.end();
fs.writeFileSync(
    'path/to/trace',
    JSON.stringify(tracing.stop()),
    'utf8',
    function() {}
);

Trie

Trie data structure.

Type Definition
class Trie {
    add(word: string): void;
    remove(word: string): void;
    has(word: string): boolean;
    words(prefix: string): string[];
    clear(): void;
}

add

Add a word to trie.

Name Desc
word Word to add

remove

Remove a word from trie.

has

Check if word exists.

words

Get all words with given Prefix.

Name Desc
prefix Word prefix
return Words with given Prefix

clear

Clear all words from trie.

const trie = new Trie();
trie.add('carpet');
trie.add('car');
trie.add('cat');
trie.add('cart');
trie.has('cat'); // -> true
trie.remove('carpet');
trie.has('carpet'); // -> false
trie.words('car'); // -> ['car', 'cart']
trie.clear();

Tween

Tween engine for JavaScript animations.

Type Definition
class Tween extends Emitter {
    constructor(target: any);
    to(props: any, duration?: number, ease?: string | Function): Tween;
    progress(): number;
    progress(progress: number): Tween;
    play(): Tween;
    pause(): Tween;
    paused(): boolean;
}

Extend from Emitter.

constructor

Name Desc
obj Values to tween

to

Name Desc
destination Final properties
duration Tween duration
ease Easing function

play

Begin playing forward.

pause

Pause the animation.

paused

Get animation paused state.

progress

Update or get animation progress.

Name Desc
progress Number between 0 and 1
const pos = { x: 0, y: 0 };

const tween = new Tween(pos);
tween
    .on('update', function(target) {
        console.log(target.x, target.y);
    })
    .on('end', function(target) {
        console.log(target.x, target.y); // -> 100, 100
    });
tween.to({ x: 100, y: 100 }, 1000, 'inElastic').play();

Url

Simple url manipulator.

Type Definition
namespace Url {
    interface IUrl {
        protocol: string;
        auth: string;
        hostname: string;
        hash: string;
        query: any;
        port: string;
        pathname: string;
        slashes: boolean;
    }
}
class Url {
    protocol: string;
    auth: string;
    hostname: string;
    hash: string;
    query: any;
    port: string;
    pathname: string;
    slashes: boolean;
    constructor(url?: string);
    setQuery(name: string, val: string | number): Url;
    setQuery(query: types.PlainObj<string | number>): Url;
    rmQuery(name: string | string[]): Url;
    toString(): string;
    static parse(url: string): Url.IUrl;
    static stringify(object: Url.IUrl): string;
}

constructor

Name Desc
url=location Url string

setQuery

Set query value.

Name Desc
name Query name
val Query value
return this
Name Desc
query query object
return this

rmQuery

Remove query value.

Name Desc
name Query name
return this

parse

[static] Parse url into an object.

Name Desc
url Url string
return Url object

stringify

[static] Stringify url object into a string.

Name Desc
url Url object
return Url string

An url object contains the following properties:

Name Desc
protocol The protocol scheme of the URL (e.g. http:)
slashes A boolean which indicates whether the protocol is followed by two forward slashes (//)
auth Authentication information portion (e.g. username:password)
hostname Host name without port number
port Optional port number
pathname URL path
query Parsed object containing query string
hash The "fragment" portion of the URL including the pound-sign (#)
const url = new Url('http://example.com:8080?eruda=true');
console.log(url.port); // -> '8080'
url.query.foo = 'bar';
url.rmQuery('eruda');
url.toString(); // -> 'http://example.com:8080/?foo=bar'

Validator

Object values validation.

Type Definition
class Validator {
    constructor(options: types.PlainObj<any>);
    validate(object: any): string | boolean;
    static plugins: any;
    static addPlugin(name: string, plugin: types.AnyFn): void;
}

constructor

Name Desc
options Validation configuration

validate

Validate object.

Name Desc
obj Object to validate
return Validation result, true means ok

addPlugin

[static] Add plugin.

Name Desc
name Plugin name
plugin Validation handler

Default Plugins

Required, number, boolean, string and regexp.

Validator.addPlugin('custom', function(val, key, config) {
    if (typeof val === 'string' && val.length === 5) return true;

    return key + ' should be a string with length 5';
});
const validator = new Validator({
    test: {
        required: true,
        custom: true
    }
});
validator.validate({}); // -> 'test is required'
validator.validate({ test: 1 }); // -> 'test should be a string with length 5';
validator.validate({ test: 'zso' }); // -> true

Wrr

Weighted Round Robin implementation.

Type Definition
class Wrr {
    size: number;
    set(val: any, weight: number): void;
    get(val: any): number | void;
    remove(val: any): void;
    clear(): void;
    next(): any;
}

size

Pool size.

set

Set a value to the pool. Weight is updated if value already exists.

Name Desc
val Value to set
weight Weight of the value

get

Get weight of given value.

Name Desc
val Value to get
return Weight of the value

remove

Remove given value.

Name Desc
val Value to remove

next

Get next value from pool.

clear

Clear all values.

const pool = new Wrr();
pool.set('A', 4);
pool.set('B', 8);
pool.set('C', 2);
pool.next();
pool.remove('A');
console.log(pool.size); // -> 2

abbrev

Calculate the set of unique abbreviations for a given set of strings.

Type Definition
function abbrev(...names: string[]): types.PlainObj<string>;
Name Desc
names List of names
return Abbreviation map
abbrev('lina', 'luna');
// -> {li: 'lina', lin: 'lina', lina: 'lina', lu: 'luna', lun: 'luna', luna: 'luna'}

after

Create a function that invokes once it's called n or more times.

Type Definition
function after<T extends types.AnyFn>(n: number, fn: T): T;
Name Desc
n Number of calls before invoked
fn Function to restrict
return New restricted function
const fn = after(5, function() {
    // -> Only invoke after fn is called 5 times.
});

ajax

Perform an asynchronous HTTP request.

Type Definition
namespace ajax {
    function get(
        url: string,
        data: string | {},
        success: types.AnyFn,
        dataType?: string
    ): XMLHttpRequest;
    function get(
        url: string,
        success: types.AnyFn,
        dataType?: string
    ): XMLHttpRequest;
    function post(
        url: string,
        data: string | {},
        success: types.AnyFn,
        dataType?: string
    ): XMLHttpRequest;
    function post(
        url: string,
        success: types.AnyFn,
        dataType?: string
    ): XMLHttpRequest;
}
function ajax(options: {
    type?: string;
    url: string;
    data?: string | {};
    dataType?: string;
    contentType?: string;
    success?: types.AnyFn;
    error?: types.AnyFn;
    complete?: types.AnyFn;
    timeout?: number;
}): XMLHttpRequest;
Name Desc
options Ajax options

Available options:

Name Desc
type=get Request type
url Request url
data Request data
dataType=json Response type(json, xml)
contentType=application/x-www-form-urlencoded Request header Content-Type
success Success callback
error Error callback
complete Callback after request
timeout Request timeout

get

Shortcut for type = GET;

post

Shortcut for type = POST;

Name Desc
url Request url
data Request data
success Success callback
dataType Response type
ajax({
    url: 'http://example.com',
    data: { test: 'true' },
    error() {},
    success(data) {
        // ...
    },
    dataType: 'json'
});

ajax.get('http://example.com', {}, function(data) {
    // ...
});

allKeys

Retrieve all the names of object's own and inherited properties.

Type Definition
namespace allKeys {
    interface IOptions {
        prototype?: boolean;
        unenumerable?: boolean;
    }
}
function allKeys(
    obj: any,
    options: { symbol: true } & allKeys.IOptions
): Array<string | Symbol>;
function allKeys(
    obj: any,
    options?: ({ symbol: false } & allKeys.IOptions) | allKeys.IOptions
): string[];
Name Desc
obj Object to query
options Options
return Array of all property names

Available options:

Name Desc
prototype=true Include prototype keys
unenumerable=false Include unenumerable keys
symbol=false Include symbol keys

Members of Object's prototype won't be retrieved.

const obj = Object.create({ zero: 0 });
obj.one = 1;
allKeys(obj); // -> ['zero', 'one']

ansiColor

Ansi colors.

Type Definition
namespace ansiColor {
    type IFn = (str: string) => string;
}
const ansiColor: {
    black: ansiColor.IFn;
    red: ansiColor.IFn;
    green: ansiColor.IFn;
    yellow: ansiColor.IFn;
    blue: ansiColor.IFn;
    magenta: ansiColor.IFn;
    cyan: ansiColor.IFn;
    white: ansiColor.IFn;
    gray: ansiColor.IFn;
    grey: ansiColor.IFn;
    bgBlack: ansiColor.IFn;
    bgRed: ansiColor.IFn;
    bgGreen: ansiColor.IFn;
    bgYellow: ansiColor.IFn;
    bgBlue: ansiColor.IFn;
    bgMagenta: ansiColor.IFn;
    bgCyan: ansiColor.IFn;
    bgWhite: ansiColor.IFn;
    blackBright: ansiColor.IFn;
    redBright: ansiColor.IFn;
    greenBright: ansiColor.IFn;
    yellowBright: ansiColor.IFn;
    blueBright: ansiColor.IFn;
    magentaBright: ansiColor.IFn;
    cyanBright: ansiColor.IFn;
    whiteBright: ansiColor.IFn;
    bgBlackBright: ansiColor.IFn;
    bgRedBright: ansiColor.IFn;
    bgGreenBright: ansiColor.IFn;
    bgYellowBright: ansiColor.IFn;
    bgBlueBright: ansiColor.IFn;
    bgMagentaBright: ansiColor.IFn;
    bgCyanBright: ansiColor.IFn;
    bgWhiteBright: ansiColor.IFn;
};

Available colors

black, red, green, yellow, blue, magenta, cyan, white, gray, grey

bgBlack, bgRed, bgGreen, bgYellow, bgBlue, bgMagenta, bgCyan, bgWhite,

blackBright, redBright, greenBright, yellowBright, blueBright, magentaBright, cyanBright, whiteBright

bgBlackBright, bgRedBright, bgGreenBright, bgYellowBright, bgBlueBright, bgMagentaBright, bgCyanBright, bgWhiteBright

ansiColor.red('Warning');

arrToMap

Make an object map using array of strings.

Type Definition
function arrToMap<T>(
    arr: string[],
    val?: T
): { [key: string]: T };
Name Desc
arr Array of strings
val=true Key value
return Object map
const needPx = arrToMap([
    'column-count',
    'columns',
    'font-weight',
    'line-weight',
    'opacity',
    'z-index',
    'zoom'
]);
const key = 'column-count';
let val = '5';
if (needPx[key]) val += 'px';
console.log(val); // -> '5px'

atob

Use Buffer to emulate atob when running in node.

Type Definition
function atob(str: string): string;
atob('SGVsbG8gV29ybGQ='); // -> 'Hello World'

average

Get average value of given numbers.

Type Definition
function average(...numbers: number[]): number;
Name Desc
numbers Numbers to calculate
return Average value
average(5, 3, 1); // -> 3

base64

Basic base64 encoding and decoding.

Type Definition
const base64: {
    encode(bytes: number[]): string;
    decode(str: string): number[];
};

encode

Turn a byte array into a base64 string.

Name Desc
bytes Byte array
return Base64 string

decode

Turn a base64 string into a byte array.

Name Desc
str Base64 string
return Byte array
base64.encode([168, 174, 155, 255]); // -> 'qK6b/w=='
base64.decode('qK6b/w=='); // -> [168, 174, 155, 255]

before

Create a function that invokes less than n times.

Type Definition
function before<T extends types.AnyFn>(n: number, fn: T): T;
Name Desc
n Number of calls at which fn is no longer invoked
fn Function to restrict
return New restricted function

Subsequent calls to the created function return the result of the last fn invocation.

const fn = before(5, function() {});
fn(); // Allow function to be call 4 times at last.

between

Determines whether a value belongs to a certain interval.

Type Definition
function between(
    number: number,
    start: number,
    end: number
): boolean;
between(2, 1, 3); // -> true
between(2, 3, 1); // -> true
between(1, 1, 3); // -> true
between(3, 1, 3); // -> false

binarySearch

Binary search implementation.

Type Definition
function binarySearch(
    array: any[],
    val: any,
    cmp?: types.AnyFn
): number;
Name Desc
array Sorted array
val Value to seek
cmp Comparator
return Value index
binarySearch([1, 2, 3], 2); // -> 1
binarySearch([1, 2], 3); // -> -1
binarySearch(
    [
        {
            key: 1
        },
        {
            key: 2
        }
    ],
    { key: 1 },
    (a, b) => {
        if (a.key === b.key) return 0;
        return a.key < b.key ? -1 : 1;
    }
); // -> 0

bind

Create a function bound to a given object.

Type Definition
function bind(
    fn: types.AnyFn,
    ctx: any,
    ...args: any[]
): types.AnyFn;
Name Desc
fn Function to bind
ctx This binding of given fn
args Optional arguments
return New bound function
const fn = bind(
    function(msg) {
        console.log(this.name + ':' + msg);
    },
    { name: 'eustia' },
    'I am a utility library.'
);
fn(); // -> 'eustia: I am a utility library.'

btoa

Use Buffer to emulate btoa when running in node.

Type Definition
function btoa(str: string): string;
btoa('Hello World'); // -> 'SGVsbG8gV29ybGQ='

bubbleSort

Bubble sort implementation.

Type Definition
function bubbleSort(arr: any[], cmp?: types.AnyFn): any[];
Name Desc
arr Array to sort
cmp Comparator
return Sorted array
bubbleSort([2, 1]); // -> [1, 2]

bytesToStr

Convert bytes to string.

Type Definition
function bytesToStr(bytes: number[], encoding?: string): string;
Name Desc
bytes Bytes array
encoding=utf8 Encoding of string
return Result string
bytesToStr([108, 105, 99, 105, 97]); // -> 'zso'

bytesToWords

Convert bytes to 32-bit words.

Type Definition
function bytesToWords(bytes: number[]): number[];

Useful when using CryptoJS.

Name Desc
bytes Byte array
return Word array
bytesToWords([0x12, 0x34, 0x56, 0x78]); // -> [0x12345678]

cacheRequire

Cache everything in module require to speed up app load.

Type Definition
function cacheRequire(options?: {
    dir?: string;
    requirePath?: boolean;
    code?: boolean;
    compileCache?: boolean;
}): void;
Name Desc
options Cache options

Available options:

Name Desc
dir Cache dir
requirePath=true Whether require path should be cached
code=false Whether js code should be cached
compileCache=true Whether compile cache should be used
cacheRequire({
    dir: 'path/to/cache/dir'
});

callbackify

Convert a function that returns a Promise to a function following the error-first callback style.

Type Definition
function callbackify(fn: types.AnyFn): types.AnyFn;
Name Desc
fn Function that returns a Promise
return Function following the error-fist callback style
function fn() {
    return new Promise(function(resolve, reject) {
        // ...
    });
}

const cbFn = callbackify(fn);

cbFn(function(err, value) {
    // ...
});

camelCase

Convert string to "camelCase".

Type Definition
function camelCase(str: string): string;
Name Desc
str String to convert
return Camel cased string
camelCase('foo-bar'); // -> fooBar
camelCase('foo bar'); // -> fooBar
camelCase('foo_bar'); // -> fooBar
camelCase('foo.bar'); // -> fooBar

capitalize

Convert the first character to upper case and the remaining to lower case.

Type Definition
function capitalize(str: string): string;
Name Desc
str String to capitalize
return Capitalized string
capitalize('rED'); // -> Red

castPath

Cast value into a property path array.

Type Definition
function castPath(path: string | string[], obj?: any): string[];
Name Desc
path Value to inspect
obj Object to query
return Property path array
castPath('a.b.c'); // -> ['a', 'b', 'c']
castPath(['a']); // -> ['a']
castPath('a[0].b'); // -> ['a', '0', 'b']
castPath('a.b.c', { 'a.b.c': true }); // -> ['a.b.c']

centerAlign

Center align text in a string.

Type Definition
function centerAlign(
    str: string | string[],
    width?: number
): string;
Name Desc
str String to align
width Total width of each line
return Center aligned string
centerAlign('test', 8); // -> '  test'
centerAlign('test\nlines', 8); // -> '  test\n lines'
centerAlign(['test', 'lines'], 8); // -> '  test\n lines'

cgroup

Read cgroup metrics inside container.

Type Definition
const cgroup: {
    cpu: {
        stat(): {
            usage: number;
        };
        max(): number;
    };
    cpuset: {
        cpus(): {
            effective: number[];
        };
    };
    memory: {
        max(): number;
        current(): number;
    };
    version(): number;
};
cgroup.cpu.stat();

char

Return string representing a character whose Unicode code point is the given integer.

Type Definition
function char(num: number): string;
Name Desc
num Integer to convert
return String representing corresponding char
char(65); // -> 'A'
char(97); // -> 'a'

chunk

Split array into groups the length of given size.

Type Definition
function chunk(arr: any[], size?: number): Array<any[]>;
Name Desc
arr Array to process
size=1 Length of each chunk
return Chunks of given size
chunk([1, 2, 3, 4], 2); // -> [[1, 2], [3, 4]]
chunk([1, 2, 3, 4], 3); // -> [[1, 2, 3], [4]]
chunk([1, 2, 3, 4]); // -> [[1], [2], [3], [4]]

clamp

Clamp number within the inclusive lower and upper bounds.

Type Definition
function clamp(n: number, lower: number, upper: number): number;
function clamp(n: number, upper: number): number;
Name Desc
n Number to clamp
lower Lower bound
upper Upper bound
return Clamped number
clamp(-10, -5, 5); // -> -5
clamp(10, -5, 5); // -> 5
clamp(2, -5, 5); // -> 2
clamp(10, 5); // -> 5
clamp(2, 5); // -> 2

className

Utility for conditionally joining class names.

Type Definition
function className(...names: any[]): string;
Name Desc
names Class names
return Joined class names
className('a', 'b', 'c'); // -> 'a b c'
className('a', false, 'b', 0, 1, 'c'); // -> 'a b 1 c'
className('a', ['b', 'c']); // -> 'a b c'
className('a', { b: false, c: true }); // -> 'a c'
className('a', ['b', 'c', { d: true, e: false }]); // -> 'a b c d';

cliHelp

Output cli help.

Type Definition
namespace cliHelp {
    interface IOption {
        name: string;
        shorthand?: string;
        desc: string;
    }
    interface ICommand {
        name: string;
        desc: string;
        usage: string | string[];
        options?: IOption[];
    }
    interface IData {
        name: string;
        usage: string | string[];
        commands: ICommand[];
    }
}
function cliHelp(data: cliHelp.IData | cliHelp.ICommand): string;
Name Desc
data Help data
return Cli help
const test = {
    name: 'test',
    desc: 'Generate test files',
    usage: ['<module-name> [options]', 'lpad --browser'],
    options: [
        {
            name: 'browser',
            shorthand: 'b',
            desc: 'True if test should run in a browser'
        }
    ]
};
const data = {
    name: 'zso',
    usage: '<command> [options]',
    commands: [test]
};

cliHelp(data);
cliHelp(test);

clone

Create a shallow-copied clone of the provided plain object.

Type Definition
function clone<T>(val: T): T;

Any nested objects or arrays will be copied by reference, not duplicated.

Name Desc
val Value to clone
return Cloned value
clone({ name: 'eustia' }); // -> {name: 'eustia'}

cloneDeep

Recursively clone value.

Type Definition
function cloneDeep<T>(val: T): T;
Name Desc
val Value to clone
return Deep cloned Value
const obj = [{ a: 1 }, { a: 2 }];
const obj2 = cloneDeep(obj);
console.log(obj[0] === obj2[1]); // -> false

cmpVersion

Compare version strings.

Type Definition
function cmpVersion(v1: string, v2: string): number;
Name Desc
v1 Version to compare
v2 Version to compare
return Comparison result
cmpVersion('1.1.8', '1.0.4'); // -> 1
cmpVersion('1.0.2', '1.0.2'); // -> 0
cmpVersion('2.0', '2.0.0'); // -> 0
cmpVersion('3.0.1', '3.0.0.2'); // -> 1
cmpVersion('1.1.1', '1.2.3'); // -> -1

combine

Create an array by using one array for keys and another for its values.

Type Definition
function combine(keys: string[], values: any[]): any;
Name Desc
keys Keys to be used
values Values to be used
return Created object
combine(['a', 'b', 'c'], [1, 2, 3]); // -> {a: 1, b: 2, c: 3}

compact

Return a copy of the array with all falsy values removed.

Type Definition
function compact(arr: any[]): any[];

The values false, null, 0, "", undefined, and NaN are falsey.

Name Desc
arr Array to compact
return New array of filtered values
compact([0, 1, false, 2, '', 3]); // -> [1, 2, 3]

compose

Compose a list of functions.

Type Definition
function compose(...fn: types.AnyFn[]): types.AnyFn;

Each function consumes the return value of the function that follows.

Name Desc
...fn Functions to compose
return Composed function
const welcome = compose(
    function(name) {
        return 'hi: ' + name;
    },
    function(name) {
        return name.toUpperCase() + '!';
    }
);

welcome('zso'); // -> 'hi: ZSO!'

compressImg

Compress image using canvas.

Type Definition
function compressImg(
    file: File | Blob | string,
    cb: types.AnyFn
): void;
function compressImg(
    file: File | Blob | string,
    options?: {
        maxWidth?: number;
        maxHeight?: number;
        width?: number;
        height?: number;
        mimeType?: string;
        quality?: number;
    },
    cb?: types.AnyFn
): void;
Name Desc
file Image file or url
options Options
cb Callback

Available options:

Name Desc
maxWidth Max width
maxHeight Max height
width Output image width
height Output image height
mimeType Mime type
quality=0.8 Image quality, range from 0 to 1

In order to keep image ratio, height will be ignored when width is set.

And maxWith, maxHeight will be ignored if width or height is set.

const file = new Blob([]);
compressImg(
    file,
    {
        maxWidth: 200
    },
    function(err, file) {
        // ...
    }
);

concat

Concat multiple arrays into a single array.

Type Definition
function concat(...args: Array<any[]>): any[];
Name Desc
...arr Arrays to concat
return Concatenated array
concat([1, 2], [3], [4, 5]); // -> [1, 2, 3, 4, 5]

contain

Check if the value is present in the list.

Type Definition
function contain(arr: any[] | {} | string, val: any): boolean;
Name Desc
target Target object
val Value to check
return True if value is present in the list
contain([1, 2, 3], 1); // -> true
contain({ a: 1, b: 2 }, 1); // -> true
contain('abc', 'a'); // -> true

container

Get container stats inside container.

Type Definition
const container: {
    cpuNum(): number;
    cpuUsage(period?: number): Promise<number>;
    cpuLoad(period?: number): Promise<number>;
    memUsage(): number;
    memLoad(): number;
};
container.cpuNum();

convertBase

Convert base of a number.

Type Definition
function convertBase(
    num: number | string,
    from: number,
    to: number
): string;
Name Desc
num Number to convert
from Base from
to Base to
return Converted number
convertBase('10', 2, 10); // -> '2'
convertBase('ff', 16, 2); // -> '11111111'

convertBin

Convert binary data type.

Type Definition
namespace convertBin {
    function blobToArrBuffer(blob: any): Promise<ArrayBuffer>;
}
function convertBin(bin: any, type: string): any;
Name Desc
bin Binary data to convert
type Binary type
return Target binary

Supported binary type

base64, ArrayBuffer, Array, Uint8Array, Blob(browser), Buffer(node)

You can not convert Blob to other types directly since it's an asynchronous process.

blobToArrBuffer

Convert Blob to ArrayBuffer.

Name Desc
blob Blob to convert
return ArrayBuffer promise
convertBin('qK6b/w==', 'Uint8Array'); // -> [168, 174, 155, 255]
convertBin.blobToArrBuffer(new Blob([])).then(arrBuffer => {
    // Do something...
});

cookie

Simple api for handling browser cookies.

Type Definition
namespace cookie {
    interface IOptions {
        path?: string;
        expires?: number;
        domain?: string;
        secure?: boolean;
    }
    interface ICookie {
        get(key: string, options?: cookie.IOptions): string;
        set(key: string, val: string, options?: cookie.IOptions): ICookie;
        remove(key: string, options?: cookie.IOptions): ICookie;
    }
}
const cookie: cookie.ICookie;

get

Get cookie value.

Name Desc
key Cookie key
return Corresponding cookie value

set

Set cookie value.

Name Desc
key Cookie key
val Cookie value
options Cookie options
return Module cookie

remove

Remove cookie value.

Name Desc
key Cookie key
options Cookie options
return Module cookie
cookie.set('a', '1', { path: '/' });
cookie.get('a'); // -> '1'
cookie.remove('a');

copy

Copy text to clipboard using document.execCommand.

Type Definition
function copy(text: string, cb?: types.AnyFn): void;
Name Desc
text Text to copy
cb Optional callback
copy('text', function(err) {
    // Handle errors.
});

crc1

CRC1 implementation.

Type Definition
function crc1(
    input: string | number[],
    previous?: number
): number;
Name Desc
input Data to calculate
previous Previous CRC1 result
return CRC1 result
crc1('1234567890').toString(16); // -> 'd'

crc16

CRC16 implementation.

Type Definition
function crc16(
    input: string | number[],
    previous?: number
): number;
Name Desc
input Data to calculate
previous Previous CRC16 result
return CRC16 result
crc16('1234567890').toString(16); // -> 'c57a'

crc32

CRC32 implementation.

Type Definition
function crc32(
    input: string | number[],
    previous?: number
): number;
Name Desc
input Data to calculate
previous Previous CRC32 result
return CRC16 result
crc32('1234567890').toString(16); // -> '261daee5'

crc8

CRC8 implementation.

Type Definition
function crc8(
    input: string | number[],
    previous?: number
): number;
Name Desc
input Data to calculate
previous Previous CRC8 result
return CRC8 result
crc8('1234567890').toString(16); // -> '52'

create

Create new object using given object as prototype.

Type Definition
function create(proto?: object): any;
Name Desc
proto Prototype of new object
return Created object
const obj = create({ a: 1 });
console.log(obj.a); // -> 1

createAssigner

Used to create extend, extendOwn and defaults.

Type Definition
function createAssigner(
    keysFn: types.AnyFn,
    defaults: boolean
): types.AnyFn;
Name Desc
keysFn Function to get object keys
defaults No override when set to true
return Result function, extend...

createUrl

CreateObjectURL wrapper.

Type Definition
function createUrl(
    data: any,
    options?: { type?: string }
): string;
Name Desc
data Url data
options Used when data is not a File or Blob
return Blob url
createUrl('test', { type: 'text/plain' }); // -> Blob url
createUrl(['test', 'test']);
createUrl(new Blob([]));
createUrl(new File(['test'], 'test.txt'));

css

Css parser and serializer.

Type Definition
const css: {
    parse(css: string): object;
    stringify(stylesheet: object, options?: { indent?: string }): string;
};

Comments will be stripped.

parse

Parse css into js object.

Name Desc
css Css string
return Parsed js object

stringify

Stringify object into css.

Name Desc
stylesheet Object to stringify
options Stringify options
return Css string

Options:

Name Desc
indent=' ' String used to indent
const stylesheet = css.parse('.name { background: #000; color: red; }');
// {type: 'stylesheet', rules: [{type: 'rule', selector: '.name', declarations: [...]}]}
css.stringify(stylesheet);

cssPriority

Calculate and compare priority of css selector/rule.

Type Definition
namespace cssPriority {
    function compare(p1: number[], p2: number[]): number;
}
function cssPriority(
    selector: string,
    options?: {
        important?: boolean;
        inlineStyle?: boolean;
        position?: number;
    }
): number[];
Name Type
selector CSS selector
options Rule extra info
return Priority array

Priority array contains five number values.

  1. Important mark
  2. Inline style
  3. ID selector
  4. Class selectors
  5. Type selectors
  6. Rule position

compare

Compare priorities.

Name Desc
p1 Priority to compare
p2 Priority to compare
return Comparison result
cssPriority('a.button > i.icon:before', {
    important: true,
    inlineStyle: false,
    position: 100
}); // -> [1, 0, 0, 2, 3, 100]

cssSupports

Check if browser supports a given CSS feature.

Type Definition
function cssSupports(name: string, val?: string): boolean;
Name Desc
name Css property name
val Css property value
return True if supports
cssSupports('display', 'flex'); // -> true
cssSupports('display', 'invalid'); // -> false
cssSupports('text-decoration-line', 'underline'); // -> true
cssSupports('grid'); // -> true
cssSupports('invalid'); // -> false

curry

Function currying.

Type Definition
function curry(fn: types.AnyFn): types.AnyFn;
Name Desc
fn Function to curry
return New curried function
const add = curry(function(a, b) {
    return a + b;
});
const add1 = add(1);
add1(2); // -> 3

dateFormat

Simple but extremely useful date format function.

Type Definition
function dateFormat(
    date: Date,
    mask: string,
    utc?: boolean,
    gmt?: boolean
): string;
function dateFormat(
    mask: string,
    utc?: boolean,
    gmt?: boolean
): string;
Name Desc
date=new Date Date object to format
mask Format mask
utc=false UTC or not
gmt=false GMT or not
return Formatted duration
Mask Desc
d Day of the month as digits; no leading zero for single-digit days
dd Day of the month as digits; leading zero for single-digit days
ddd Day of the week as a three-letter abbreviation
dddd Day of the week as its full name
m Month as digits; no leading zero for single-digit months
mm Month as digits; leading zero for single-digit months
mmm Month as a three-letter abbreviation
mmmm Month as its full name
yy Year as last two digits; leading zero for years less than 10
yyyy Year represented by four digits
h Hours; no leading zero for single-digit hours (12-hour clock)
hh Hours; leading zero for single-digit hours (12-hour clock)
H Hours; no leading zero for single-digit hours (24-hour clock)
HH Hours; leading zero for single-digit hours (24-hour clock)
M Minutes; no leading zero for single-digit minutes
MM Minutes; leading zero for single-digit minutes
s Seconds; no leading zero for single-digit seconds
ss Seconds; leading zero for single-digit seconds
l L Milliseconds. l gives 3 digits. L gives 2 digits
t Lowercase, single-character time marker string: a or p
tt Lowercase, two-character time marker string: am or pm
T Uppercase, single-character time marker string: A or P
TT Uppercase, two-character time marker string: AM or PM
Z US timezone abbreviation, e.g. EST or MDT
o GMT/UTC timezone offset, e.g. -0500 or +0230
S The date's ordinal suffix (st, nd, rd, or th)
UTC: Must be the first four characters of the mask
dateFormat('isoDate'); // -> 2016-11-19
dateFormat('yyyy-mm-dd HH:MM:ss'); // -> 2016-11-19 19:00:04
dateFormat(new Date(), 'yyyy-mm-dd'); // -> 2016-11-19

debounce

Return a new debounced version of the passed function.

Type Definition
function debounce<T extends types.AnyFn>(fn: T, wait: number): T;
Name Desc
fn Function to debounce
wait Number of milliseconds to delay
return New debounced function
const calLayout = debounce(function() {}, 300);
// $(window).resize(calLayout);

debug

A tiny JavaScript debugging utility.

Type Definition
function debug(name: string): any;
Name Desc
name Namespace
return Function to print decorated log
const d = debug('test');
d('doing lots of uninteresting work');
d.enabled = false;

deburr

Convert Latin-1 Supplement and Latin Extended-A letters to basic Latin letters and remove combining diacritical marks.

Type Definition
function deburr(str: string): string;
Name Desc
str String to deburr
return Deburred string
deburr('déjà vu'); // -> 'deja vu'

decodeUriComponent

Better decodeURIComponent that does not throw if input is invalid.

Type Definition
function decodeUriComponent(str: string): string;
Name Desc
str String to decode
return Decoded string
decodeUriComponent('%%25%'); // -> '%%%'
decodeUriComponent('%E0%A4%A'); // -> '\xE0\xA4%A'

defaults

Fill in undefined properties in object with the first value present in the following list of defaults objects.

Type Definition
function defaults(obj: any, ...src: any[]): any;
Name Desc
obj Destination object
...src Sources objects
return Destination object
defaults({ name: 'RedHood' }, { name: 'Unknown', age: 24 }); // -> {name: 'RedHood', age: 24}

define

Define a module, should be used along with use.

Type Definition
function define(
    name: string,
    requires: string[],
    method: types.AnyFn
): void;
function define(name: string, method: types.AnyFn): void;
Name Desc
name Module name
requires Dependencies
method Module body

The module won't be executed until it's used by use function.

define('A', function() {
    return 'A';
});
define('B', ['A'], function(A) {
    return 'B' + A;
});

defineProp

Shortcut for Object.defineProperty(defineProperties).

Type Definition
function defineProp<T>(
    obj: T,
    prop: string,
    descriptor: PropertyDescriptor
): T;
function defineProp<T>(
    obj: T,
    descriptor: PropertyDescriptorMap
): T;
Name Desc
obj Object to define
prop Property path
descriptor Property descriptor
return Object itself
Name Desc
obj Object to define
prop Property descriptors
return Object itself
const obj = { b: { c: 3 }, d: 4, e: 5 };
defineProp(obj, 'a', {
    get: function() {
        return this.e * 2;
    }
});
// obj.a is equal to 10
defineProp(obj, 'b.c', {
    set: function(val) {
        // this is pointed to obj.b
        this.e = val;
    }.bind(obj)
});
obj.b.c = 2;
// obj.a is equal to 4

const obj2 = { a: 1, b: 2, c: 3 };
defineProp(obj2, {
    a: {
        get: function() {
            return this.c;
        }
    },
    b: {
        set: function(val) {
            this.c = val / 2;
        }
    }
});
// obj2.a is equal to 3
obj2.b = 4;
// obj2.a is equal to 2

defined

Return the first argument that is not undefined.

Type Definition
function defined(...args: any[]): any;
Name Desc
...args Arguments to check
return First defined argument
defined(false, 2, void 0, 100); // -> false

delRequireCache

Delete node.js require cache.

Type Definition
function delRequireCache(id: string): void;
Name Desc
id Module name or path
const zso = require('zso');
zso.a = 5;
delRequireCache('zso');
require('zso').a; // -> undefined

delay

Invoke function after certain milliseconds.

Type Definition
function delay(
    fn: types.AnyFn,
    wait: number,
    ...args: any[]
): void;
Name Desc
fn Function to delay
wait Number of milliseconds to delay invocation
...args Arguments to invoke fn with
delay(
    function(text) {
        console.log(text);
    },
    1000,
    'later'
);
// -> Logs 'later' after one second

delegate

Event delegation.

Type Definition
const delegate: {
    add(el: Element, type: string, selector: string, cb: types.AnyFn): void;
    remove(el: Element, type: string, selector: string, cb: types.AnyFn): void;
};

add

Add event delegation.

Name Desc
el Parent element
type Event type
selector Match selector
cb Event callback

remove

Remove event delegation.

const container = document.getElementById('container');
function clickHandler() {
    // Do something...
}
delegate.add(container, 'click', '.children', clickHandler);
delegate.remove(container, 'click', '.children', clickHandler);

deprecate

Node.js util.deprecate with browser support.

Type Definition
function deprecate(fn: types.AnyFn, msg: string): types.AnyFn;
Name Desc
fn Function to be deprecated
msg Warning message
return Deprecated function
const fn = () => {};
const obsoleteFn = deprecate(fn, 'obsoleteFn is deprecated.');
obsoleteFn();

detectBrowser

Detect browser info using ua.

Type Definition
function detectBrowser(
    ua?: string
): {
    name: string;
    version: number;
};
Name Desc
ua=navigator.userAgent Browser userAgent
return Object containing name and version

Browsers supported: ie, chrome, edge, firefox, opera, safari, ios(mobile safari), android(android browser)

const browser = detectBrowser();
if (browser.name === 'ie' && browser.version < 9) {
    // Do something about old IE...
}

detectMocha

Detect if mocha is running.

Type Definition
function detectMocha(): boolean;
detectMocha(); // -> True if mocha is running.

detectOs

Detect operating system using ua.

Type Definition
function detectOs(ua?: string): string;
Name Desc
ua=navigator.userAgent Browser userAgent
return Operating system name

Supported os: windows, os x, linux, ios, android, windows phone

if (detectOs() === 'ios') {
    // Do something about ios...
}

difference

Create an array of unique array values not included in the other given array.

Type Definition
function difference(arr: any[], ...args: any[]): any[];
Name Desc
arr Array to inspect
...args Values to exclude
return New array of filtered values
difference([3, 2, 1], [4, 2]); // -> [3, 1]

dotCase

Convert string to "dotCase".

Type Definition
function dotCase(str: string): string;
Name Desc
str String to convert
return Dot cased string
dotCase('fooBar'); // -> foo.bar
dotCase('foo bar'); // -> foo.bar

download

Trigger a file download on client side.

Type Definition
function download(
    data: Blob | File | string | any[],
    name: string,
    type?: string
): void;
Name Desc
data Data to download
name File name
type=text/plain Data type
download('test', 'test.txt');

durationFormat

Simple duration format function.

Type Definition
function durationFormat(duration: number, mask?: string): string;
Name Desc
duration Duration to format, millisecond
mask='hh:mm:ss' Format mask
return Formatted duration
Mask Desc
d Days
h Hours
m Minutes
s Seconds
l Milliseconds
durationFormat(12345678); // -> '03:25:45'
durationFormat(12345678, 'h:m:s:l'); // -> '3:25:45:678'

each

Iterate over elements of collection and invokes iterator for each element.

Type Definition
function each<T>(
    list: types.List<T>,
    iterator: types.ListIterator<T, void>,
    ctx?: any
): types.List<T>;
function each<T>(
    object: types.Dictionary<T>,
    iterator: types.ObjectIterator<T, void>,
    ctx?: any
): types.Collection<T>;
Name Desc
obj Collection to iterate over
iterator Function invoked per iteration
ctx Function context
each({ a: 1, b: 2 }, function(val, key) {});

easing

Easing functions adapted from http://jqueryui.com/ .

Type Definition
const easing: {
    linear(percent: number): number;
    inQuad(percent: number): number;
    outQuad(percent: number): number;
    inOutQuad(percent: number): number;
    outInQuad(percent: number): number;
    inCubic(percent: number): number;
    outCubic(percent: number): number;
    inQuart(percent: number): number;
    outQuart(percent: number): number;
    inQuint(percent: number): number;
    outQuint(percent: number): number;
    inExpo(percent: number): number;
    outExpo(percent: number): number;
    inSine(percent: number): number;
    outSine(percent: number): number;
    inCirc(percent: number): number;
    outCirc(percent: number): number;
    inElastic(percent: number, elasticity?: number): number;
    outElastic(percent: number, elasticity?: number): number;
    inBack(percent: number): number;
    outBack(percent: number): number;
    inOutBack(percent: number): number;
    outInBack(percent: number): number;
    inBounce(percent: number): number;
    outBounce(percent: number): number;
};
Name Desc
percent Number between 0 and 1
return Calculated number
easing.linear(0.5); // -> 0.5
easing.inElastic(0.5, 500); // -> 0.03125

emulateTouch

Emulate touch events on desktop browsers.

Type Definition
function emulateTouch(el: Element): void;
Name Desc
el Target element
const el = document.querySelector('#test');
emulateTouch(el);
el.addEventListener('touchstart', () => {}, false);

endWith

Check if string ends with the given target string.

Type Definition
function endWith(str: string, suffix: string): boolean;
Name Desc
str The string to search
suffix String suffix
return True if string ends with target
endWith('ab', 'b'); // -> true

escape

Escapes a string for insertion into HTML, replacing &, <, >, ", `, and ' characters.

Type Definition
function escape(str: string): string;
Name Desc
str String to escape
return Escaped string
escape('You & Me'); // -> 'You &amp; Me'

escapeJsStr

Escape string to be a valid JavaScript string literal between quotes.

Type Definition
function escapeJsStr(str: string): string;

http://www.ecma-international.org/ecma-262/5.1/#sec-7.8.4

Name Desc
str String to escape
return Escaped string
escapeJsStr('"\n'); // -> '\\"\\\\n'

escapeRegExp

Escape special chars to be used as literals in RegExp constructors.

Type Definition
function escapeRegExp(str: string): string;
Name Desc
str String to escape
return Escaped string
escapeRegExp('[zso]'); // -> '\\[zso\\]'

evalCss

Load css into page.

Type Definition
function evalCss(css: string): HTMLStyleElement;
Name Desc
css Css code
return Style element
evalCss('body{background:#08c}');

evalJs

Execute js in given context.

Type Definition
function evalJs(js: string, ctx?: any): void;
Name Desc
js JavaScript code
ctx=global Context
evalJs('5+2'); // -> 7
evalJs('this.a', { a: 2 }); // -> 2

every

Check if predicate return truthy for all elements.

Type Definition
function every<T>(
    object: types.List<T>,
    iterator?: types.ListIterator<T, boolean>,
    context?: any
): boolean;
function every<T>(
    object: types.Dictionary<T>,
    iterator?: types.ObjectIterator<T, boolean>,
    context?: any
): boolean;
Name Desc
object Collection to iterate over
iterator Function invoked per iteration
context Predicate context
return True if all elements pass the predicate check
every([2, 4], function(val) {
    return val % 2 === 0;
}); // -> true

extend

Copy all of the properties in the source objects over to the destination object.

Type Definition
function extend(destination: any, ...sources: any[]): any;
Name Desc
destination Destination object
...sources Sources objects
return Destination object
extend({ name: 'RedHood' }, { age: 24 }); // -> {name: 'RedHood', age: 24}

extendDeep

Recursive object extending.

Type Definition
function extendDeep(destination: any, ...sources: any[]): any;
Name Desc
destination Destination object
...sources Sources objects
return Destination object
extendDeep(
    {
        name: 'RedHood',
        family: {
            mother: 'Jane',
            father: 'Jack'
        }
    },
    {
        family: {
            brother: 'Bruce'
        }
    }
);
// -> {name: 'RedHood', family: {mother: 'Jane', father: 'Jack', brother: 'Bruce'}}

extendOwn

Like extend, but only copies own properties over to the destination object.

Type Definition
function extendOwn(destination: any, ...sources: any[]): any;
Name Desc
destination Destination object
...sources Sources objects
return Destination object
extendOwn({ name: 'RedHood' }, { age: 24 }); // -> {name: 'RedHood', age: 24}

extractBlockCmts

Extract block comments from source code.

Type Definition
function extractBlockCmts(str: string): string[];
Name Desc
str String to extract
return Block comments
extractBlockCmts('/*zso*/'); // -> ['zso']

extractUrls

Extract urls from plain text.

Type Definition
function extractUrls(str: string): string[];
Name Desc
str Text to extract
return Url list
const str = '[Official site: http://eustia.ooo9.io](http://eustia.ooo9.io)';
extractUrls(str); // -> ['http://eustia.ooo9.io']

fetch

Turn XMLHttpRequest into promise like.

Type Definition
namespace fetch {
    interface IResult {
        ok: boolean;
        status: number;
        statusText: string;
        url: string;
        clone(): IResult;
        text(): Promise<string>;
        json(): Promise<any>;
        xml(): Promise<Document | null>;
        blob(): Promise<Blob>;
        headers: {
            keys(): string[];
            entries(): Array<string[]>;
            get(name: string): string;
            has(name: string): boolean;
        };
    }
}
function fetch(
    url: string,
    options?: {
        method?: string;
        timeout?: number;
        headers?: types.PlainObj<string>;
        body?: any;
    }
): Promise<fetch.IResult>;

Note: This is not a complete fetch pollyfill.

Name Desc
url Request url
options Request options
return Request promise
fetch('test.json', {
    method: 'GET',
    timeout: 3000,
    headers: {},
    body: ''
})
    .then(function(res) {
        return res.json();
    })
    .then(function(data) {
        console.log(data);
    });

fibonacci

Calculate fibonacci number.

Type Definition
function fibonacci(n: number): number;
Name Desc
n Index of fibonacci sequence
return Expected fibonacci number
fibonacci(1); // -> 1
fibonacci(3); // -> 2

fileSize

Turn bytes into human readable file size.

Type Definition
function fileSize(bytes: number): string;
Name Desc
bytes File bytes
return Readable file size
fileSize(5); // -> '5'
fileSize(1500); // -> '1.46K'
fileSize(1500000); // -> '1.43M'
fileSize(1500000000); // -> '1.4G'
fileSize(1500000000000); // -> '1.36T'

fileType

Detect file type using magic number.

Type Definition
function fileType(
    input: Buffer | ArrayBuffer | Uint8Array
):
    | {
          ext: string;
          mime: string;
      }
    | undefined;
Name Desc
input File input
return Object containing ext and mime

Supported file types

jpg, png, gif, webp, bmp, gz, zip, rar, pdf, exe

const fs = require('fs');
const file = fs.readFileSync('path/to/file');
console.log(fileType(file)); // -> { ext: 'jpg', mime: 'image/jpeg' }

fileUrl

Convert a file path to a file URL.

Type Definition
function fileUrl(path: string): string;
Name Desc
path File path
return File URL
fileUrl('c:\\foo\\bar'); // -> 'file:///c:/foo/bar'

fill

Fill elements of array with value.

Type Definition
function fill(
    list: any[],
    val: any,
    start?: number,
    end?: number
): any[];
Name Desc
list Array to fill
val Value to fill array with
start=0 Start position
end=arr.length End position
return Filled array
fill([1, 2, 3], '*'); // -> ['*', '*', '*']
fill([1, 2, 3], '*', 1, 2); // -> [1, '*', 3]

filter

Iterates over elements of collection, returning an array of all the values that pass a truth test.

Type Definition
function filter<T>(
    list: types.List<T>,
    iterator: types.ListIterator<T, boolean>,
    context?: any
): T[];
function filter<T>(
    object: types.Dictionary<T>,
    iterator: types.ObjectIterator<T, boolean>,
    context?: any
): T[];
Name Desc
obj Collection to iterate over
predicate Function invoked per iteration
ctx Predicate context
return Array of all values that pass predicate
filter([1, 2, 3, 4, 5], function(val) {
    return val % 2 === 0;
}); // -> [2, 4]

find

Find the first value that passes a truth test in a collection.

Type Definition
function find<T>(
    object: types.List<T>,
    iterator: types.ListIterator<T, boolean>,
    context?: any
): T | undefined;
function find<T>(
    object: types.Dictionary<T>,
    iterator: types.ObjectIterator<T, boolean>,
    context?: any
): T | undefined;
Name Desc
object Collection to iterate over
iterator Function invoked per iteration
context Predicate context
return First value that passes predicate
find(
    [
        {
            name: 'john',
            age: 24
        },
        {
            name: 'jane',
            age: 23
        }
    ],
    function(val) {
        return val.age === 23;
    }
); // -> {name: 'jane', age: 23}

findIdx

Return the first index where the predicate truth test passes.

Type Definition
function findIdx(arr: any[], predicate: types.AnyFn): number;
Name Desc
arr Array to search
predicate Function invoked per iteration
return Index of matched element
findIdx(
    [
        {
            name: 'john',
            age: 24
        },
        {
            name: 'jane',
            age: 23
        }
    ],
    function(val) {
        return val.age === 23;
    }
); // -> 1

findKey

Return the first key where the predicate truth test passes.

Type Definition
function findKey(
    obj: any,
    predicate: types.AnyFn,
    ctx?: any
): string | void;
Name Desc
obj Object to search
predicate Function invoked per iteration
ctx Predicate context
return Key of matched element
findKey({ a: 1, b: 2 }, function(val) {
    return val === 1;
}); // -> a

findLastIdx

Return the last index where the predicate truth test passes.

Type Definition
function findLastIdx(arr: any[], predicate: types.AnyFn): number;
Name Desc
arr Array to search
predicate Function invoked per iteration
return Last index of matched element
findLastIdx(
    [
        {
            name: 'john',
            age: 24
        },
        {
            name: 'jane',
            age: 23
        },
        {
            name: 'kitty',
            age: 24
        }
    ],
    function(val) {
        return val.age === 24;
    }
); // -> 2

flatten

Recursively flatten an array.

Type Definition
function flatten(arr: any[]): any[];
Name Desc
arr Array to flatten
return New flattened array
flatten(['a', ['b', ['c']], 'd', ['e']]); // -> ['a', 'b', 'c', 'd', 'e']

fnArgs

Validate function arguments.

Type Definition
function fnArgs(types: string[], args: any): void;
Name Desc
types Argument types
args Argument object

It throws an exception when validation failed.

function test(a, b, c) {
    fnArgs(['number|string', '?Function', '...number'], arguments);
    // Do something.
}
test(15);
test('test', () => {});
test('test', () => {}, 5);
test(); // Throw error
test('test', 'test'); // Throw error
test('test', () => {}, 5, 'test'); // Throw error

fnParams

Get a function parameter's names.

Type Definition
function fnParams(fn: types.AnyFn | string): string[];
Name Desc
fn Function to get parameters
return Names
fnParams(function(a, b) {}); // -> ['a', 'b']

fnv1a

Simple FNV-1a implementation.

Type Definition
function fnv1a(str: string): number;
Name Desc
str String to hash
return Hast result
fnv1a('test'); // -> 2949673445

format

Format string in a printf-like format.

Type Definition
function format(str: string, ...values: any[]): string;
Name Desc
str String to format
...values Values to replace format specifiers
return Formatted string

Format Specifiers

Specifier Desc
%s String
%d, %i Integer
%f Floating point value
%o Object
format('%s_%s', 'foo', 'bar'); // -> 'foo_bar'

fraction

Convert number to fraction.

Type Definition
function fraction(num: number): string;
Name Desc
num Number to convert
return Corresponding fraction
fraction(1.2); // -> '6/5'

freeze

Shortcut for Object.freeze.

Type Definition
function freeze<T>(obj: T): T;

Use Object.defineProperties if Object.freeze is not supported.

Name Desc
obj Object to freeze
return Object passed in
const a = { b: 1 };
freeze(a);
a.b = 2;
console.log(a); // -> {b: 1}

freezeDeep

Recursively use Object.freeze.

Type Definition
function freezeDeep<T>(obj: T): T;
Name Desc
obj Object to freeze
return Object passed in
const a = { b: { c: 1 } };
freezeDeep(a);
a.b.c = 2;
console.log(a); // -> {b: {c: 1}}

fs

Promised version of node.js fs module.

Type Definition
const fs: {
    readFile(path: string, encoding: string): Promise<string>;
    readFile(path: string): Promise<Buffer>;
    exists(path: string): Promise<boolean>;
    unlink(path: string): Promise<void>;
    writeFile(path: string, data: string, options?: string): Promise<void>;
    writeFile(path: string, data: Buffer): Promise<void>;
    readdir(path: string): Promise<string[]>;
    rmdir(path: string): Promise<void>;
    [key: string]: any;
};
fs.readFile('test.js')
    .then(function(data) {
        // Do something
    })
    .catch(function(err) {
        // Handle errors
    });

fullscreen

Fullscreen api wrapper.

Type Definition
namespace fullscreen {
    interface IFullscreen extends Emitter {
        request(el?: Element): void;
        exit(): void;
        toggle(el?: Element): void;
        isActive(): boolean;
        getEl(): Element | null;
        isEnabled(): boolean;
    }
}
const fullscreen: fullscreen.IFullscreen;

request

Request fullscreen.

Name Desc
el Fullscreen element

exit

Exit fullscreen.

toggle

Toggle fullscreen.

Name Desc
el Fullscreen element

isActive

Check Whether fullscreen is active.

getEl

Return Fullscreen element if exists.

isEnabled

Whether you are allowed to enter fullscreen.

fullscreen.request();
fullscreen.isActive(); // -> false, not a synchronous api
fullscreen.on('error', () => {});
fullscreen.on('change', () => {});

fuzzySearch

Simple fuzzy search.

Type Definition
function fuzzySearch(
    needle: string,
    haystack: any[],
    options?: {
        caseSensitive?: boolean;
        key?: string | string[];
    }
): any[];
Name Desc
needle String to search
haystacks Search list
options Search options

Available options:

Name Desc
caseSensitive=false Whether comparisons should be case sensitive
key Object key path if item is object
fuzzySearch('lic', ['zso', 'll', 'lic']); // -> ['lic', 'zso']
fuzzySearch(
    'alpha-test',
    [
        {
            name: 'alpha-test-1'
        },
        {
            name: 'beta-test'
        }
    ],
    {
        key: 'name'
    }
); // -> [{ name: 'alpha-test-1' }]

gcd

Compute the greatest common divisor using Euclid's algorithm.

Type Definition
function gcd(a: number, b: number): number;
Name Desc
a Number to calculate
b Number to calculate
return Greatest common divisor
gcd(121, 44); // -> 11

getPort

Get an available TCP port.

Type Definition
function getPort(
    port?: number | number[],
    host?: string
): Promise<number>;
Name Desc
port Preferred ports
host Host address
return Available port

If preferred ports are not available, a random port will be returned.

getPort([3000, 3001], '127.0.0.1').then(port => {
    console.log(port);
});

getProto

Get prototype of an object.

Type Definition
function getProto(obj: any): any;
Name Desc
obj Target object
return Prototype of given object, null if not exists
const a = {};
getProto(Object.create(a)); // -> a

getUrlParam

Get url param.

Type Definition
function getUrlParam(
    name: string,
    url?: string
): string | undefined;
Name Desc
name Param name
url=location Url to get param
return Param value
getUrlParam('test', 'http://example.com/?test=true'); // -> 'true'

golangify

Handle errors like golang.

Type Definition
function golangify<T, U = Error>(
    fn: (...args: any[]) => Promise<T>
): (...args: any[]) => Promise<[T | undefined, U | null]>;
function golangify<T, U = Error>(
    p: Promise<T>
): Promise<[T | undefined, U | null]>;
Name Desc
fn Function that returns a Promise
return Like fn, but resolves with [result, error]
Name Desc
p Promise to transform
return Promise that resolves with [result, error]
(async () => {
    let fnA = golangify(async () => {
        throw Error('err');
    });
    await fnA(); // -> [undefined, Error]
    let fnB = golangify(async num => num * 2);
    await fnB(2); // -> [4, null]

    await golangify(Promise.reject(Error('err'))); // -> [undefined, Error]
    await golangify(Promise.resolve(4)); // -> [4, null]
})();

h

Create html with JavaScript.

Type Definition
function h(
    tag: string,
    attrs?: types.PlainObj<any>,
    ...child: Array<string | HTMLElement>
): HTMLElement;
Name Desc
tag Tag name
attrs Attributes
...child Children
return Created element
const el = h(
    'div#test.title',
    {
        onclick: function() {},
        title: 'test'
    },
    'inner text'
);
document.body.appendChild(el);

has

Checks if key is a direct property.

Type Definition
function has(obj: {}, key: string): boolean;
Name Desc
obj Object to query
key Path to check
return True if key is a direct property
has({ one: 1 }, 'one'); // -> true

heapSort

Heap sort implementation.

Type Definition
function heapSort(arr: any[], cmp?: types.AnyFn): any[];
Name Desc
arr Array to sort
cmp Comparator
return Sorted array
heapSort([2, 1]); // -> [1, 2]

hex

Hex encoding and decoding.

Type Definition
const hex: {
    encode(bytes: number[]): string;
    decode(str: string): number[];
};

encode

Turn a byte array into a hex string.

Name Desc
bytes Byte array
return hex string

decode

Turn a hex string into a byte array.

Name Desc
str hex string
return Byte array
hex.encode([168, 174, 155, 255]); // -> 'a8ae9bff'
hex.decode('a8ae9bff'); // -> [168, 174, 155, 255]

highlight

Highlight code.

Type Definition
function highlight(
    str: string,
    lang?: string,
    style?: {
        comment?: string;
        string?: string;
        number?: string;
        keyword?: string;
        operator?: string;
    }
): string;
Name Desc
str Code string
lang=js Language, js, html or css
style Keyword highlight style
return Highlighted html code string

Available styles:

comment, string, number, keyword, operator

highlight('const a = 5;', 'js', {
    keyword: 'color:#569cd6;'
}); // -> '<span class="keyword" style="color:#569cd6;">const</span> a <span class="operator" style="color:#994500;">=</span> <span class="number" style="color:#0086b3;">5</span>;'

hookFn

Monitor, change function arguments and result.

Type Definition
function hookFn<T>(
    fn: T,
    options: {
        before?: types.AnyFn;
        after?: types.AnyFn;
        error?: types.AnyFn;
    }
): T;
Name Desc
fn Function to hook
options Hook options
return Hooked function

Available options:

Name Desc
before Arguments handler
after Result handler
error Error handler
let sum = function(a, b) {
    if (a > 100) {
        throw Error('a is bigger than 100');
    }
    return a + b;
};
let totalSum = 0;
sum = hookFn(sum, {
    before(a, b) {
        return [+a, +b];
    },
    after(result) {
        totalSum += result;
        return totalSum;
    },
    error() {
        return totalSum;
    }
});
sum('2', '5'); // -> 7

hotkey

Capture keyboard input to trigger given events.

Type Definition
const hotkey: {
    on(key: string, listener: types.AnyFn): void;
    off(key: string, listener: types.AnyFn): void;
};

on

Register keyboard listener.

Name Desc
key Key string
listener Key listener

off

Unregister keyboard listener.

hotkey.on('k', function() {
    console.log('k is pressed');
});
function keyDown() {}
hotkey.on('shift+a, shift+b', keyDown);
hotkey.off('shift+a', keyDown);

hslToRgb

Convert hsl to rgb.

Type Definition
function hslToRgb(hsl: number[]): number[];
Name Desc
hsl Hsl values
return Rgb values
hslToRgb([165, 59, 50, 0.8]); // -> [52, 203, 165, 0.8]

html

Html parser and serializer.

Type Definition
const html: {
    parse(html: string): any[];
    stringify(tree: any[]): string;
};

parse

Parse html string into js object.

Name Desc
html Html string
return Parsed js object

stringify

Stringify object into an html string.

Name Desc
tree Object to stringify
return Html string
const tree = html.parse('<div id="name">zso</div>');
// -> [{tag: 'div', attrs: {id: 'name'}, content: ['zso']}]
html.stringify(tree);

identity

Return the first argument given.

Type Definition
function identity<T>(val: T): T;
Name Desc
val Any value
return Given value
identity('a'); // -> 'a'

idxOf

Get the index at which the first occurrence of value.

Type Definition
function idxOf(arr: any[], val: any, fromIdx?: number): number;
Name Desc
arr Array to search
val Value to search for
fromIdx=0 Index to search from
return Value index
idxOf([1, 2, 1, 2], 2, 2); // -> 3

indent

Indent each line in a string.

Type Definition
function indent(
    str: string,
    char?: string,
    len?: number
): string;
Name Desc
str String to indent
char Character to prepend
len Indent length
return Indented string
indent('foo\nbar', ' ', 4); // -> '    foo\n    bar'

inherits

Inherit the prototype methods from one constructor into another.

Type Definition
function inherits(
    Class: types.AnyFn,
    SuperClass: types.AnyFn
): void;
Name Desc
Class Child Class
SuperClass Super Class
function People(name) {
    this._name = name;
}
People.prototype = {
    getName: function() {
        return this._name;
    }
};
function Student(name) {
    this._name = name;
}
inherits(Student, People);
const s = new Student('RedHood');
s.getName(); // -> 'RedHood'

ini

Ini parser and serializer.

Type Definition
const ini: {
    parse(ini: string): any;
    stringify(
        obj: any,
        options?: {
            section?: string;
            whitespace: boolean;
        }
    ): string;
};

parse

Parse ini string into js object.

Name Desc
ini Ini string
return Parsed js object

stringify

Stringify object into an ini formatted string.

Name Desc
obj Object to stringify
options Stringify options
return Ini formatted string

Options:

Name Desc
section Top section
whitespace=false Whitespace around =
const config = ini.parse(`
; This is a comment
library = zso

[user.info]
name = surunzi
alias[] = ooo9
alias[] = red
`); // -> {library: 'zso', user: {info: {name: 'surunzi', alias: ['ooo9', 'red']}}}

ini.stringify(config);

insertionSort

Insertion sort implementation.

Type Definition
function insertionSort(arr: any[], cmp?: types.AnyFn): any[];
Name Desc
arr Array to sort
cmp Comparator
return Sorted array
insertionSort([2, 1]); // -> [1, 2]

intersect

Compute the list of values that are the intersection of all the arrays.

Type Definition
function intersect(...arr: Array<any[]>): any[];
Name Desc
...arr Arrays to inspect
return New array of inspecting values
intersect([1, 2, 3, 4], [2, 1, 10], [2, 1]); // -> [1, 2]

intersectRange

Intersect two ranges.

Type Definition
namespace intersectRange {
    interface IRange {
        start: number;
        end: number;
    }
}
function intersectRange(
    a: intersectRange.IRange,
    b: intersectRange.IRange
): intersectRange.IRange | void;
Name Desc
a Range a
b Range b
return Intersection if exist
intersectRange({ start: 0, end: 12 }, { start: 11, end: 13 });
// -> {start: 11, end: 12}
intersectRange({ start: 0, end: 5 }, { start: 6, end: 7 });
// -> undefined

invariant

Facebook's invariant.

Type Definition
function invariant(
    condition: boolean,
    format?: string,
    a?: string,
    b?: string,
    c?: string,
    d?: string,
    e?: string,
    f?: string
): void;

Related docs

invariant(true, 'This will not throw');
// No errors
invariant(false, 'This will throw an error with this message');
// Error: Invariant Violation: This will throw an error with this message

invert

Create an object composed of the inverted keys and values of object.

Type Definition
function invert(obj: any): any;
Name Desc
obj Object to invert
return New inverted object

If object contains duplicate values, subsequent values overwrite property assignments of previous values.

invert({ a: 'b', c: 'd', e: 'f' }); // -> {b: 'a', d: 'c', f: 'e'}

isAbsoluteUrl

Check if an url is absolute.

Type Definition
function isAbsoluteUrl(url: string): boolean;
Name Desc
url Url to check
return True if url is absolute
isAbsoluteUrl('http://www.surunzi.com'); // -> true
isAbsoluteUrl('//www.surunzi.com'); // -> false
isAbsoluteUrl('surunzi.com'); // -> false

isArgs

Check if value is classified as an arguments object.

Type Definition
function isArgs(val: any): boolean;
Name Desc
val Value to check
return True if value is an arguments object
isArgs(
    (function() {
        return arguments;
    })()
); // -> true

isArr

Check if value is an Array object.

Type Definition
function isArr(val: any): boolean;
Name Desc
val Value to check
return True if value is an Array object
isArr([]); // -> true
isArr({}); // -> false

isArrBuffer

Check if value is an ArrayBuffer.

Type Definition
function isArrBuffer(val: any): boolean;
Name Desc
val Value to check
return True if value is an ArrayBuffer
isArrBuffer(new ArrayBuffer(8)); // -> true

isArrLike

Check if value is array-like.

Type Definition
function isArrLike(val: any): boolean;
Name Desc
val Value to check
return True if value is array like

Function returns false.

isArrLike('test'); // -> true
isArrLike(document.body.children); // -> true;
isArrLike([1, 2, 3]); // -> true

isAsyncFn

Check if value is an async function.

Type Definition
function isAsyncFn(val: any): boolean;
Name Desc
val Value to check
return True if value is an async function
isAsyncFn(function*() {}); // -> false
isAsyncFn(function() {}); // -> false
isAsyncFn(async function() {}); // -> true

isBlob

Check if value is a Blob.

Type Definition
function isBlob(val: any): boolean;
Name Desc
val Value to check
return True if value is a Blob
isBlob(new Blob([])); // -> true;
isBlob([]); // -> false

isBool

Check if value is a boolean primitive.

Type Definition
function isBool(val: any): boolean;
Name Desc
val Value to check
return True if value is a boolean
isBool(true); // -> true
isBool(false); // -> true
isBool(1); // -> false

isBrowser

Check if running in a browser.

Type Definition
const isBrowser: boolean;
console.log(isBrowser); // -> true if running in a browser

isBuffer

Check if value is a buffer.

Type Definition
function isBuffer(val: any): boolean;
Name Desc
val The value to check
return True if value is a buffer
isBuffer(new Buffer(4)); // -> true

isClose

Check if values are close(almost equal) to each other.

Type Definition
function isClose(
    a: number,
    b: number,
    relTol?: number,
    absTol?: number
): boolean;

abs(a-b) <= max(relTol * max(abs(a), abs(b)), absTol)

Name Desc
a Number to compare
b Number to compare
relTol=1e-9 Relative tolerance
absTol=0 Absolute tolerance
return True if values are close
isClose(1, 1.0000000001); // -> true
isClose(1, 2); // -> false
isClose(1, 1.2, 0.3); // -> true
isClose(1, 1.2, 0.1, 0.3); // -> true

isCyclic

Detect cyclic object reference.

Type Definition
function isCyclic(val: any): boolean;
Name Desc
val Value to detect
return True if value is cyclic
isCyclic({}); // -> false
const obj = { a: 1 };
obj.b = obj;
isCyclic(obj); // -> true

isDarkMode

Detect dark mode.

Type Definition
function isDarkMode(): boolean;
console.log(isDarkMode()); // true if dark mode

isDataUrl

Check if a string is a valid data url.

Type Definition
function isDataUrl(str: string): boolean;
Name Desc
str String to check
return True if string is a data url
isDataUrl('http://eustia.ooo9.io'); // -> false
isDataUrl('data:text/plain;base64,SGVsbG8sIFdvcmxkIQ%3D%3D'); // -> true

isDate

Check if value is classified as a Date object.

Type Definition
function isDate(val: any): boolean;
Name Desc
val value to check
return True if value is a Date object
isDate(new Date()); // -> true

isDir

Check if a path is directory.

Type Definition
function isDir(path: string): Promise<boolean>;
Name Desc
path Path to check
return True if path is a directory
isDir('/foo/bar');

isDocker

Check if the process is running inside a docker container.

Type Definition
function isDocker(): boolean;
console.log(isDocker()); // -> true if running inside a docker container.

isEl

Check if value is a DOM element.

Type Definition
function isEl(val: any): boolean;
Name Desc
val Value to check
return True if value is a DOM element
isEl(document.body); // -> true

isEmail

Loosely validate an email address.

Type Definition
function isEmail(val: string): boolean;
Name Desc
val Value to check
return True if value is an email like string
isEmail('surunzi@foxmail.com'); // -> true

isEmpty

Check if value is an empty object or array.

Type Definition
function isEmpty(val: any): boolean;
Name Desc
val Value to check
return True if value is empty
isEmpty([]); // -> true
isEmpty({}); // -> true
isEmpty(''); // -> true

isEqual

Performs an optimized deep comparison between the two objects, to determine if they should be considered equal.

Type Definition
function isEqual(val: any, other: any): boolean;
Name Desc
val Value to compare
other Other value to compare
return True if values are equivalent
isEqual([1, 2, 3], [1, 2, 3]); // -> true

isErr

Check if value is an error.

Type Definition
function isErr(val: any): boolean;
Name Desc
val Value to check
return True if value is an error
isErr(new Error()); // -> true

isEven

Check if number is even.

Type Definition
function isEven(num: number): boolean;
Name Desc
num Number to check
return True if number is even
isEven(0); // -> true
isEven(1); // -> false
isEven(2); // -> true

isFile

Check if value is a file.

Type Definition
function isFile(val: any): boolean;
Name Desc
val Value to check
return True if value is a file
isFile(new File(['test'], 'test.txt', { type: 'text/plain' })); // -> true

isFinite

Check if value is a finite primitive number.

Type Definition
function isFinite(val: any): boolean;
Name Desc
val Value to check
return True if value is a finite number
isFinite(3); // -> true
isFinite(Infinity); // -> false

isFn

Check if value is a function.

Type Definition
function isFn(val: any): boolean;
Name Desc
val Value to check
return True if value is a function

Generator function is also classified as true.

isFn(function() {}); // -> true
isFn(function*() {}); // -> true
isFn(async function() {}); // -> true

isFullWidth

Check if character is full width.

Type Definition
function isFullWidth(codePoint: number): boolean;
Name Desc
codePoint Unicode code point
return True if character is full width
isFullWidth('a'.codePointAt(0)); // -> false
isFullWidth(','.codePointAt(0)); // -> false
isFullWidth('我'.codePointAt(0)); // -> true
isFullWidth(','.codePointAt(0)); // -> true

isGeneratorFn

Check if value is a generator function.

Type Definition
function isGeneratorFn(val: any): boolean;
Name Desc
val Value to check
return True if value is a generator function
isGeneratorFn(function*() {}); // -> true
isGeneratorFn(function() {}); // -> false

isHidden

Check if element is hidden.

Type Definition
function isHidden(
    el: Element,
    options?: {
        display?: boolean;
        visibility?: boolean;
        opacity?: boolean;
        size?: boolean;
        viewport?: boolean;
        overflow?: boolean;
    }
): boolean;
Name Desc
el Target element
options Check options
return True if element is hidden

Available options:

Name Desc
display=true Check if it is displayed
visibility=false Check visibility css property
opacity=false Check opacity css property
size=false Check width and height
viewport=false Check if it is in viewport
overflow=false Check if hidden in overflow
isHidden(document.createElement('div')); // -> true

isInt

Checks if value is classified as a Integer.

Type Definition
function isInt(val: any): boolean;
Name Desc
val Value to check
return True if value is correctly classified
isInt(5); // -> true
isInt(5.1); // -> false
isInt({}); // -> false

isIp

Check if value is an IP address.

Type Definition
namespace isIp {
    function v4(str: string): boolean;
    function v6(str: string): boolean;
}
function isIp(str: string): boolean;
Name Desc
str String to check
return True if value is an IP address

v4

Check if value is an IPv4 address.

v6

Check if value is an IPv6 address.

isIp('192.168.191.1'); // -> true
isIp('1:2:3:4:5:6:7:8'); // -> true
isIp('test'); // -> false
isIp.v4('192.168.191.1'); // -> true
isIp.v6('1:2:3:4:5:6:7:8'); // -> true

isJson

Check if value is a valid JSON.

Type Definition
function isJson(val: string): boolean;

It uses JSON.parse() and a try... catch block.

Name Desc
val JSON string
return True if value is a valid JSON
isJson('{"a": 5}'); // -> true
isJson("{'a': 5}"); // -> false

isLeapYear

Check if a year is a leap year.

Type Definition
function isLeapYear(year: number): boolean;
Name Desc
year Year to check
return True if year is a leap year
isLeapYear(2000); // -> true
isLeapYear(2002); // -> false

isMap

Check if value is a Map object.

Type Definition
function isMap(val: any): boolean;
Name Desc
val Value to check
return True if value is a Map
isMap(new Map()); // -> true
isMap(new WeakMap()); // -> false

isMatch

Check if keys and values in src are contained in obj.

Type Definition
function isMatch(obj: any, src: any): boolean;
Name Desc
obj Object to inspect
src Object of property values to match
return True if object is match
isMatch({ a: 1, b: 2 }, { a: 1 }); // -> true

isMiniProgram

Check if running in wechat mini program.

Type Definition
const isMiniProgram: boolean;
console.log(isMiniProgram); // -> true if running in mini program.

isMobile

Check whether client is using a mobile browser using ua.

Type Definition
function isMobile(ua?: string): boolean;
Name Desc
ua=navigator.userAgent User agent
return True if ua belongs to mobile browsers
isMobile(navigator.userAgent);

isNaN

Check if value is an NaN.

Type Definition
function isNaN(val: any): boolean;
Name Desc
val Value to check
return True if value is an NaN

Undefined is not an NaN, different from global isNaN function.

isNaN(0); // -> false
isNaN(NaN); // -> true

isNative

Check if value is a native function.

Type Definition
function isNative(val: any): boolean;
Name Desc
val Value to check
return True if value is a native function
isNative(function() {}); // -> false
isNative(Math.min); // -> true

isNil

Check if value is null or undefined, the same as value == null.

Type Definition
function isNil(val: any): boolean;
Name Desc
val Value to check
return True if value is null or undefined
isNil(null); // -> true
isNil(void 0); // -> true
isNil(undefined); // -> true
isNil(false); // -> false
isNil(0); // -> false
isNil([]); // -> false

isNode

Check if running in node.

Type Definition
const isNode: boolean;
console.log(isNode); // -> true if running in node

isNull

Check if value is an Null.

Type Definition
function isNull(val: any): boolean;
Name Desc
val Value to check
return True if value is an Null
isNull(null); // -> true

isNum

Check if value is classified as a Number primitive or object.

Type Definition
function isNum(val: any): boolean;
Name Desc
val Value to check
return True if value is correctly classified
isNum(5); // -> true
isNum(5.1); // -> true
isNum({}); // -> false

isNumeric

Check if value is numeric.

Type Definition
function isNumeric(val: any): boolean;
Name Desc
val Value to check
return True if value is numeric
isNumeric(1); // -> true
isNumeric('1'); // -> true
isNumeric(Number.MAX_VALUE); // -> true
isNumeric(0xff); // -> true
isNumeric(''); // -> false
isNumeric('1.1.1'); // -> false
isNumeric(NaN); // -> false

isObj

Check if value is the language type of Object.

Type Definition
function isObj(val: any): boolean;
Name Desc
val Value to check
return True if value is an object

Language Spec

isObj({}); // -> true
isObj([]); // -> true

isOdd

Check if number is odd.

Type Definition
function isOdd(num: number): boolean;
Name Desc
num Number to check
return True if number is odd
isOdd(0); // -> false
isOdd(1); // -> true
isOdd(2); // -> false

isPlainObj

Check if value is an object created by Object constructor.

Type Definition
function isPlainObj(val: any): boolean;
Name Desc
val Value to check
return True if value is a plain object
isPlainObj({}); // -> true
isPlainObj([]); // -> false
isPlainObj(function() {}); // -> false

isPortFree

Check if a TCP port is free.

Type Definition
function isPortFree(
    port: number,
    host?: string
): Promise<boolean>;
Name Desc
port TCP port
host Host address
return True if given port is free
isPortFree(3000).then(isFree => {
    // Do something.
});

isPrime

Check if the provided integer is a prime number.

Type Definition
function isPrime(num: number): boolean;
Name Desc
num Number to check
return True if number is a prime number
isPrime(11); // -> true
isPrime(8); // -> false

isPrimitive

Check if value is string, number, boolean or null.

Type Definition
function isPrimitive(val: any): boolean;
Name Desc
val Value to check
return True if value is a primitive
isPrimitive(5); // -> true
isPrimitive('abc'); // -> true
isPrimitive(false); // -> true

isPromise

Check if value looks like a promise.

Type Definition
function isPromise(val: any): boolean;
Name Desc
val Value to check
return True if value looks like a promise
isPromise(new Promise(function() {})); // -> true
isPromise({}); // -> false

isRegExp

Check if value is a regular expression.

Type Definition
function isRegExp(val: any): boolean;
Name Desc
val Value to check
return True if value is a regular expression
isRegExp(/a/); // -> true

isRelative

Check if path appears to be relative.

Type Definition
function isRelative(path: string): boolean;
Name Desc
path Path to check
return True if path appears to be relative
isRelative('README.md'); // -> true

isRetina

Determine if running on a high DPR device or not.

Type Definition
const isRetina: boolean;
console.log(isRetina); // -> true if high DPR

isRunning

Check if process is running.

Type Definition
function isRunning(pid: number): boolean;
Name Desc
pid Process id
return True if process is running
isRunning(123456); // true if running

isSet

Check if value is a Set object.

Type Definition
function isSet(val: any): boolean;
Name Desc
val Value to check
return True if value is a Set
isSet(new Set()); // -> true
isSet(new WeakSet()); // -> false

isSorted

Check if an array is sorted.

Type Definition
function isSorted(arr: any[], cmp?: types.AnyFn): boolean;
Name Desc
arr Array to check
cmp Comparator
return True if array is sorted
isSorted([1, 2, 3]); // -> true
isSorted([3, 2, 1]); // -> false

isStr

Check if value is a string primitive.

Type Definition
function isStr(val: any): boolean;
Name Desc
val Value to check
return True if value is a string primitive
isStr('zso'); // -> true

isStream

Check if value is a Node.js stream.

Type Definition
function isStream(val: any): boolean;
Name Desc
val Value to check
return True if value is a Node.js stream
const stream = require('stream');

isStream(new stream.Stream()); // -> true

isSymbol

Check if value is a symbol.

Type Definition
function isSymbol(val: any): boolean;
Name Desc
val Value to check
return True if value is a symbol
isSymbol(Symbol('test')); // -> true

isTypedArr

Check if value is a typed array.

Type Definition
function isTypedArr(val: any): boolean;
Name Desc
val Value to check
return True if value is a typed array
isTypedArr([]); // -> false
isTypedArr(new Uint8Array(8)); // -> true

isUndef

Check if value is undefined.

Type Definition
function isUndef(val: any): boolean;
Name Desc
val Value to check
return True if value is undefined
isUndef(void 0); // -> true
isUndef(null); // -> false

isUrl

Loosely validate an url.

Type Definition
function isUrl(val: string): boolean;
Name Desc
val Value to check
return True if value is an url like string
isUrl('http://www.example.com?foo=bar&param=test'); // -> true

isWeakMap

Check if value is a WeakMap object.

Type Definition
function isWeakMap(val: any): boolean;
Name Desc
val Value to check
return True if value is a WeakMap
isWeakMap(new Map()); // -> false
isWeakMap(new WeakMap()); // -> true

isWeakSet

Check if value is a WeakSet object.

Type Definition
function isWeakSet(val: any): boolean;
Name Desc
val Value to check
return True if value is a WeakSet
isWeakSet(new Set()); // -> false
isWeakSet(new WeakSet()); // -> true

isWindows

Check if platform is windows.

Type Definition
const isWindows: boolean;
console.log(isWindows); // -> true if running on windows

jsonClone

Use JSON parse and stringify to clone object.

Type Definition
function jsonClone<T>(val: T): T;
Name Desc
val Value to clone
return Cloned value
jsonClone({ name: 'zso' }); // -> { name: 'zso' }

jsonp

A simple jsonp implementation.

Type Definition
function jsonp(options: {
    url: string;
    data?: any;
    success?: types.AnyFn;
    param?: string;
    name?: string;
    error?: types.AnyFn;
    complete?: types.AnyFn;
    timeout?: number;
}): void;
Name Desc
options Jsonp Options

Available options:

Name Desc
url Request url
data Request data
success Success callback
param=callback Callback param
name Callback name
error Error callback
complete Callback after request
timeout Request timeout
jsonp({
    url: 'http://example.com',
    data: { test: 'true' },
    success: function(data) {
        // ...
    }
});

kebabCase

Convert string to "kebabCase".

Type Definition
function kebabCase(str: string): string;
Name Desc
str String to convert
return Kebab cased string
kebabCase('fooBar'); // -> foo-bar
kebabCase('foo bar'); // -> foo-bar
kebabCase('foo_bar'); // -> foo-bar
kebabCase('foo.bar'); // -> foo-bar

keyCode

Key codes and key names conversion.

Type Definition
function keyCode(name: string): number;
function keyCode(code: number): string;

Get key code's name.

Name Desc
code Key code
return Corresponding key name

Get key name's code.

Name Desc
name Key name
return Corresponding key code
keyCode(13); // -> 'enter'
keyCode('enter'); // -> 13

keys

Create an array of the own enumerable property names of object.

Type Definition
function keys(obj: any): string[];
Name Desc
obj Object to query
return Array of property names
keys({ a: 1 }); // -> ['a']

kill

Kill process.

Type Definition
function kill(pid: number): void;
Name Desc
pid Process ID
kill(9420);

last

Get the last element of array.

Type Definition
function last(arr: any[]): any;
Name Desc
arr The array to query
return The last element of array
last([1, 2]); // -> 2

lazyImport

Import modules lazily, Proxy is used.

Type Definition
function lazyImport<T>(
    importFn: (moduleId: string) => T,
    dirname?: string
): (moduleId: string) => T;
Name Desc
importFn Actual function to require module
dirname Current file folder
return New function to require module
const r = lazyImport(require);

const _ = r('underscore');

_.isNumber(5);

lazyRequire

Require modules lazily.

Type Definition
function lazyRequire<T>(
    requireFn: (moduleId: string) => T
): (moduleId: string) => T;
const r = lazyRequire(require);

const _ = r('underscore');

// underscore is required only when _ is called.
_().isNumber(5);

levenshtein

Levenshtein distance implementation.

Type Definition
function levenshtein(a: string, b: string): number;
Name Desc
a First string
b Second string
return Levenshtein distance between a and b
levenshtein('cat', 'cake'); // -> 2

linkify

Hyperlink urls in a string.

Type Definition
function linkify(str: string, hyperlink?: types.AnyFn): string;
Name Desc
str String to hyperlink
hyperlink Function to hyperlink url
return Result string
const str = 'Official site: http://eustia.ooo9.io';
linkify(str); // -> 'Official site: <a href="http://eustia.ooo9.io">http://eustia.ooo9.io</a>'
linkify(str, function(url) {
    return '<a href="' + url + '" target="_blank">' + url + '</a>';
});

loadCss

Inject link tag into page with given href value.

Type Definition
function loadCss(src: string, cb?: types.AnyFn): void;
Name Desc
src Style source
cb Onload callback
loadCss('style.css', function(isLoaded) {
    // Do something...
});

loadImg

Load image with given src.

Type Definition
function loadImg(src: string, cb?: types.AnyFn): void;
Name Desc
src Image source
cb Onload callback
loadImg('http://eustia.ooo9.io/img.jpg', function(err, img) {
    console.log(img.width, img.height);
});

loadJs

Inject script tag into page with given src value.

Type Definition
function loadJs(src: string, cb?: types.AnyFn): void;
Name Desc
src Script source
cb Onload callback
loadJs('main.js', function(isLoaded) {
    // Do something...
});

longest

Get the longest item in an array.

Type Definition
function longest(arr: string[]): string;
Name Desc
arr Array to inspect
return Longest item
longest(['a', 'abcde', 'abc']); // -> 'abcde'

lowerCase

Convert string to lower case.

Type Definition
function lowerCase(str: string): string;
Name Desc
str String to convert
return Lower cased string
lowerCase('TEST'); // -> 'test'

lpad

Pad string on the left side if it's shorter than length.

Type Definition
function lpad(str: string, len: number, chars?: string): string;
Name Desc
str String to pad
len Padding length
chars String used as padding
return Result string
lpad('a', 5); // -> '    a'
lpad('a', 5, '-'); // -> '----a'
lpad('abc', 3, '-'); // -> 'abc'
lpad('abc', 5, 'ab'); // -> 'ababc'

ltrim

Remove chars or white-spaces from beginning of string.

Type Definition
function ltrim(str: string, chars?: string | string[]): string;
Name Desc
str String to trim
chars Characters to trim
return Trimmed string
ltrim(' abc  '); // -> 'abc  '
ltrim('_abc_', '_'); // -> 'abc_'
ltrim('_abc_', ['a', '_']); // -> 'bc_'

map

Create an array of values by running each element in collection through iteratee.

Type Definition
function map<T, TResult>(
    list: types.List<T>,
    iterator: types.ListIterator<T, TResult>,
    context?: any
): TResult[];
function map<T, TResult>(
    object: types.Dictionary<T>,
    iterator: types.ObjectIterator<T, TResult>,
    context?: any
): TResult[];
Name Desc
object Collection to iterate over
iterator Function invoked per iteration
context Function context
return New mapped array
map([4, 8], function(n) {
    return n * n;
}); // -> [16, 64]

mapObj

Map for objects.

Type Definition
function mapObj<T, TResult>(
    object: types.Dictionary<T>,
    iterator: types.ObjectIterator<T, TResult>,
    context?: any
): types.Dictionary<TResult>;
Name Desc
object Object to iterate over
iterator Function invoked per iteration
context Function context
return New mapped object
mapObj({ a: 1, b: 2 }, function(val, key) {
    return val + 1;
}); // -> {a: 2, b: 3}

matcher

Return a predicate function that checks if attrs are contained in an object.

Type Definition
function matcher(attrs: any): types.AnyFn;
Name Desc
attrs Object of property values to match
return New predicate function
const filter = require('zso/filter');

const objects = [
    { a: 1, b: 2, c: 3 },
    { a: 4, b: 5, c: 6 }
];
filter(objects, matcher({ a: 4, c: 6 })); // -> [{a: 4, b: 5, c: 6}]

max

Get maximum value of given numbers.

Type Definition
function max(...num: number[]): number;
Name Desc
...num Numbers to calculate
return Maximum value
max(2.3, 1, 4.5, 2); // 4.5

md5

MD5 implementation.

Type Definition
function md5(msg: string | number[]): string;
Name Desc
msg Message to encrypt
return MD5 hash
md5('zso'); // -> 'e59f337d85e9a467f1783fab282a41d0'

memStorage

Memory-backed implementation of the Web Storage API.

Type Definition
const memStorage: typeof window.localStorage;

A replacement for environments where localStorage or sessionStorage is not available.

const localStorage = window.localStorage || memStorage;
localStorage.setItem('test', 'zso');

memoize

Memoize a given function by caching the computed result.

Type Definition
function memoize(
    fn: types.AnyFn,
    hashFn?: types.AnyFn
): types.AnyFn;
Name Desc
fn Function to have its output memoized
hashFn Function to create cache key
return New memoized function
const fibonacci = memoize(function(n) {
    return n < 2 ? n : fibonacci(n - 1) + fibonacci(n - 2);
});

mergeArr

Merge the contents of arrays together into the first array.

Type Definition
function mergeArr<T, U>(
    first: ArrayLike<T>,
    ...arrays: ArrayLike<U>[]
): ArrayLike<T | U>;
Name Desc
first Array to merge
arrays Arrays to merge into the first array
return First array
const a = [1, 2];
mergeArr(a, [3, 4], [5, 6]);
console.log(a); // -> [1, 2, 3, 4, 5, 6]

mergeSort

Merge sort implementation.

Type Definition
function mergeSort(arr: any[], cmp?: types.AnyFn): any[];

Note: It's not an "in-place" sort.

Name Desc
arr Array to sort
cmp Comparator
return Sorted array
mergeSort([2, 1]); // -> [1, 2]

meta

Document meta manipulation, turn name and content into key value pairs.

Type Definition
namespace meta {
    function remove(nameList: string | string[]): void;
}
function meta(): {};
function meta(key: string): string;
function meta(keys: string[]): {};
function meta(key, value): void;
function meta(pairs: {}): void;

Get meta content with given name. If name is omitted, all pairs will be return.

Name Desc
name Meta name
return Meta content

Set meta content.

Name Desc
name Meta name
content Meta content
Name Desc
metas Object of name content pairs

remove

Remove metas.

Name Desc
name Meta name
// <meta name="a" content="1"/> <meta name="b" content="2"/> <meta name="c" content="3"/>
meta(); // -> {a: '1', b: '2', c: '3'}
meta('a'); // -> '1'
meta(['a', 'c']); // -> {a: '1', c: '3'}
meta('d', '4');
meta({
    d: '5',
    e: '6',
    f: '7'
});
meta.remove('d');
meta.remove(['e', 'f']);

methods

Return a sorted list of the names of every method in an object.

Type Definition
function methods(obj: any): string[];
Name Desc
obj Object to check
return Function names in object
methods(console); // -> ['Console', 'assert', 'dir', ...]

mime

Common mime types.

Type Definition
function mime(name: string): string | undefined;
Name Desc
name Extension
return Mime type
Name Desc
name Mime type
return Extension

It contains only the most common file types.

mime('jpg'); // -> 'image/jpeg'
mime('bmp'); // -> 'image/bmp'
mime('video/mp4'); // -> 'mp4'
mime('test'); // -> undefined

min

Get minimum value of given numbers.

Type Definition
function min(...num: number[]): number;
Name Desc
...num Numbers to calculate
return Minimum value
min(2.3, 1, 4.5, 2); // 1

mkdir

Recursively create directories.

Type Definition
namespace mkdir {
    function sync(dir: string, mode?: number): void;
}
function mkdir(
    dir: string,
    mode?: number,
    cb?: types.AnyFn
): void;
function mkdir(dir: string, cb?: types.AnyFn): void;
Name Desc
dir Directory to create
mode=0777 Directory mode
cb Callback

sync

Synchronous version.

mkdir('/tmp/foo/bar/baz', function(err) {
    if (err) console.log(err);
    else console.log('Done');
});
mkdir.sync('/tmp/foo2/bar/baz');

moment

Tiny moment.js like implementation.

Type Definition
namespace moment {
    class M {
        constructor(value: string | Date);
        format(mask: string): string;
        isValid(): boolean;
        isLeapYear(): boolean;
        isSame(that: M): boolean;
        valueOf(): number;
        isBefore(that: M): boolean;
        isAfter(that: M): boolean;
        year(): number;
        year(number): M;
        month(): number;
        month(number): M;
        date(): number;
        date(number): M;
        hour(): number;
        hour(number): M;
        minute(): number;
        minute(number): M;
        second(): number;
        second(number): M;
        millisecond(): number;
        millisecond(number): M;
        unix(): number;
        clone(): M;
        toDate(): Date;
        toArray(): number[];
        toJSON(): string;
        toISOString(): string;
        toObject(): any;
        toString(): string;
        set(unit: string, num: number): M;
        startOf(unit: string): M;
        endOf(unit: string): M;
        daysInMonth(): number;
        add(num: number, unit: string): M;
        subtract(num: number, unit: string): M;
        diff(input: M | string | Date, unit: string, asFloat: boolean): number;
    }
}
function moment(value: string | Date): moment.M;

It only supports a subset of moment.js api.

Available methods

format, isValid, isLeapYear, isSame, isBefore, isAfter, year, month, date, hour, minute, second, millisecond, unix, clone, toDate, toArray, toJSON, toISOString, toObject, toString, set, startOf, endOf, add, subtract, diff

Not supported

locale and units like quarter and week.

Note: Format uses dateFormat module, so the mask is not quite the same as moment.js.

moment('20180501').format('yyyy-mm-dd'); // -> '2018-05-01'

morphDom

Morph a dom tree to match a target dom tree.

Type Definition
function morphDom(from: Node, to: Node | string): Node;
Name Type
from Node to morph
to Node to be morphed
return Morphed node
const el1 = document.createElement('div');
el1.className = 'test';
const el2 = document.createElement('div');
el2.className = 'zso';
morphDom(el1, el2);
console.log(el1.className); // -> 'zso'

morse

Morse code encoding and decoding.

Type Definition
const morse: {
    encode(txt: string): string;
    decode(morse: string): string;
};

encode

Turn text into Morse code.

Name Desc
txt Text to encode
return Morse code

decode

Decode Morse code into text.

Name Desc
morse Morse code
return Decoded string
const str = morse.encode('Hello, world.');
// -> '.... . .-.. .-.. --- --..-- ....... .-- --- .-. .-.. -.. .-.-.-'
morse.decode(str); // -> 'Hello, world.'

ms

Convert time string formats to milliseconds.

Type Definition
function ms(str: string): number;
function ms(num: number): string;

Turn time string into milliseconds.

Name Desc
str String format
return Milliseconds

Turn milliseconds into time string.

Name Desc
num Milliseconds
return String format
ms('1s'); // -> 1000
ms('1m'); // -> 60000
ms('1.5h'); // -> 5400000
ms('1d'); // -> 86400000
ms('1y'); // -> 31557600000
ms('1000'); // -> 1000
ms(1500); // -> '1.5s'
ms(60000); // -> '1m'

naturalSort

Sort values in natural order.

Type Definition
function naturalSort<T extends any[]>(arr: T): T;
Name Desc
arr Array of values
return Sorted array
naturalSort(['img12', 'img11', '$img', '_img', '1', '2', '12']);
// -> ['1', '2', '12', '$img', 'img11', 'img12', '_img']
naturalSort([2, '1', 13]); // -> ['1', 2, 13]

negate

Create a function that negates the result of the predicate function.

Type Definition
function negate<T extends types.AnyFn>(predicate: T): T;
Name Desc
predicate Predicate to negate
return New function
function even(n) {
    return n % 2 === 0;
}
[1, 2, 3, 4, 5, 6].filter(negate(even)); // -> [1, 3, 5]

nextTick

Next tick for both node and browser.

Type Definition
function nextTick(cb: types.AnyFn): void;
Name Desc
cb Function to call

Use process.nextTick if available.

Otherwise setImmediate or setTimeout is used as fallback.

nextTick(function() {
    // Do something...
});

noop

A no-operation function.

Type Definition
function noop(): void;
noop(); // Does nothing

normalizeHeader

Normalize http header name.

Type Definition
function normalizeHeader(header: string): string;
Name Desc
header Header to normalize
return Normalized header
normalizeHeader('content-type'); // -> 'Content-Type'
normalizeHeader('etag'); // -> 'ETag'

normalizePath

Normalize file path slashes.

Type Definition
function normalizePath(path: string): string;
Name Desc
path Path to normalize
return Normalized path
normalizePath('\\foo\\bar\\'); // -> '/foo/bar/'
normalizePath('./foo//bar'); // -> './foo/bar'

normalizePhone

Normalize phone numbers into E.164 format.

Type Definition
function normalizePhone(
    phone: string,
    options: {
        countryCode: number;
        trunkPrefix?: boolean;
    }
): string;
Name Desc
phone Phone to normalize
options Normalize options
return Normalized phone

Available options:

Name Desc
countryCode Country code
trunkPrefix=false True if local format has trunk prefix
normalizePhone('13512345678', {
    countryCode: 86
}); // -> '+8613512345678'
normalizePhone('(415) 555-2671', {
    countryCode: 1
}); // -> '+14155552671'
normalizePhone('020 7183 8750', {
    countryCode: 44,
    trunkPrefix: true
}); // -> '+442071838750'

notify

Wrapper for the Web Notifications API.

Type Definition
namespace notify {
    class Notification extends Emitter {
        constructor(title: string, options?: object);
        show(): void;
    }
}
function notify(title: string, options?: object): void;
Name Desc
title Notification title
options Notification options

You can pass exactly the same options supported in the Web Notification.

Notification

Use this to create instance when certain events like close, show, click or error needed to be handled.

notify('zso', {
    body: 'This is the notification content'
});
const notification = new notify.Notification('zso', {
    body: 'This is the notification content'
});
notification.on('error', err => console.log(err));
notification.on('click', e => console.log(e));
notification.show();

now

Gets the number of milliseconds that have elapsed since the Unix epoch.

Type Definition
function now(): number;
now(); // -> 1468826678701

objToStr

Alias of Object.prototype.toString.

Type Definition
function objToStr(val: any): string;
Name Desc
val Source value
return String representation of given value
objToStr(5); // -> '[object Number]'

omit

Opposite of pick.

Type Definition
function omit(
    obj: any,
    filter: string | string[] | Function
): any;
Name Desc
obj Source object
filter Object filter
return Filtered object
omit({ a: 1, b: 2 }, 'a'); // -> {b: 2}
omit({ a: 1, b: 2, c: 3 }, ['b', 'c']); // -> {a: 1}
omit({ a: 1, b: 2, c: 3, d: 4 }, function(val, key) {
    return val % 2;
}); // -> {b: 2, d: 4}

once

Create a function that invokes once.

Type Definition
function once(fn: types.AnyFn): types.AnyFn;
Name Desc
fn Function to restrict
return New restricted function
function init() {}
const initOnce = once(init);
initOnce();
initOnce(); // -> init is invoked once

open

Open stuff like url, files.

Type Definition
function open(target: string): any;
Name Desc
target Stuff to open
return Child process
open('https://eustia.ooo9.io/');

openFile

Open file dialog to select file in browser.

Type Definition
function openFile(options?: {
    accept?: string;
    multiple?: boolean;
}): Promise<File[]>;
Name Desc
options Dialog options
return Files promise

Available options:

Name Desc
accept File types
multiple=false Select multiple files or not
openFile({ multiple: true }).then(fileList => {
    console.log(fileList);
});

optimizeCb

Used for function context binding.

Type Definition
function optimizeCb(
    fn: types.AnyFn,
    ctx: any,
    argCount?: number
): types.AnyFn;

ordinal

Add ordinal indicator to number.

Type Definition
function ordinal(num: number): string;
Name Desc
num Number to add indicator
return Result ordinal number
ordinal(1); // -> '1st'
ordinal(2); // -> '2nd'

orientation

Screen orientation helper.

Type Definition
namespace orientation {
    interface IOrientation extends Emitter {
        get(): string;
    }
}
const orientation: orientation.IOrientation;

on

Bind change event.

off

Unbind change event.

get

Get current orientation(landscape or portrait).

orientation.on('change', function(direction) {
    console.log(direction); // -> 'portrait'
});
orientation.get(); // -> 'landscape'

pad

Pad string on the left and right sides if it's shorter than length.

Type Definition
function pad(str: string, len: number, chars?: string): string;
Name Desc
str String to pad
len Padding length
chars String used as padding
return Result string
pad('a', 5); // -> '  a  '
pad('a', 5, '-'); // -> '--a--'
pad('abc', 3, '-'); // -> 'abc'
pad('abc', 5, 'ab'); // -> 'babca'
pad('ab', 5, 'ab'); // -> 'ababa'

pairs

Convert an object into a list of [key, value] pairs.

Type Definition
function pairs(obj: any): Array<any[]>;
Name Desc
obj Object to convert
return List of [key, value] pairs
pairs({ a: 1, b: 2 }); // -> [['a', 1], ['b', 2]]

parallel

Run an array of functions in parallel.

Type Definition
function parallel(tasks: types.AnyFn[], cb?: types.AnyFn): void;
Name Desc
tasks Array of functions
cb Callback once completed
parallel(
    [
        function(cb) {
            setTimeout(function() {
                cb(null, 'one');
            }, 200);
        },
        function(cb) {
            setTimeout(function() {
                cb(null, 'two');
            }, 100);
        }
    ],
    function(err, results) {
        // results -> ['one', 'two']
    }
);

parseArgs

Parse command line argument options, the same as minimist.

Type Definition
function parseArgs(
    args: string[],
    options: {
        names: any;
        shorthands: any;
    }
): any;
Name Desc
args Argument array
options Parse options
return Parsed result

options

Name Desc
names option names
shorthands option shorthands
parseArgs(['eustia', '--output', 'util.js', '-w'], {
    names: {
        output: 'string',
        watch: 'boolean'
    },
    shorthands: {
        output: 'o',
        watch: 'w'
    }
});
// -> {remain: ['eustia'], output: 'util.js', watch: true}

parseHtml

Simple html parser.

Type Definition
function parseHtml(
    html: string,
    handlers: {
        start?: (tag: string, attrs: any, unary: boolean) => void;
        end?: (tag: string) => void;
        comment?: (text: string) => void;
        text?: (text: string) => void;
    }
): void;
Name Desc
html Html to parse
handler Handlers
parseHtml('<div>zso</div>', {
    start: (tag, attrs, unary) => {},
    end: tag => {},
    comment: text => {},
    text: text => {}
});

partial

Partially apply a function by filling in given arguments.

Type Definition
function partial(
    fn: types.AnyFn,
    ...partials: any[]
): types.AnyFn;
Name Desc
fn Function to partially apply arguments to
...partials Arguments to be partially applied
return New partially applied function
const sub5 = partial(function(a, b) {
    return b - a;
}, 5);
sub5(20); // -> 15

pascalCase

Convert string to "pascalCase".

Type Definition
function pascalCase(str: string): string;
Name Desc
str String to convert
return Pascal cased string
pascalCase('fooBar'); // -> FooBar
pascalCase('foo bar'); // -> FooBar
pascalCase('foo_bar'); // -> FooBar
pascalCase('foo.bar'); // -> FooBar

perfNow

High resolution time up to microsecond precision.

Type Definition
function perfNow(): number;
const start = perfNow();

// Do something.

console.log(perfNow() - start);

pick

Return a filtered copy of an object.

Type Definition
function pick(
    object: any,
    filter: string | string[] | Function
): any;
Name Desc
object Source object
filter Object filter
return Filtered object
pick({ a: 1, b: 2 }, 'a'); // -> {a: 1}
pick({ a: 1, b: 2, c: 3 }, ['b', 'c']); // -> {b: 2, c: 3}
pick({ a: 1, b: 2, c: 3, d: 4 }, function(val, key) {
    return val % 2;
}); // -> {a: 1, c: 3}

pipe

Pipe all streams together.

Type Definition
import stream = require('stream');
function pipe(...streams: stream.Stream[]): void;
Name Desc
...streams Streams to pipe
const fs = require('fs');
const through = require('zso/through');
pipe(
    fs.createReadStream('in.txt'),
    through(function(chunk, enc, cb) {
        this.push(chunk);
        cb();
    }),
    fs.createWriteStream('out.txt')
);

pluck

Extract a list of property values.

Type Definition
function pluck(object: any, key: string | string[]): any[];
Name Desc
obj Collection to iterate over
key Property path
return New array of specified property
const stooges = [
    { name: 'moe', age: 40 },
    { name: 'larry', age: 50 },
    { name: 'curly', age: 60 }
];
pluck(stooges, 'name'); // -> ['moe', 'larry', 'curly']

precision

Find decimal precision of a given number.

Type Definition
function precision(num: number): number;
Name Desc
num Number to check
return Precision
precision(1.234); // -> 3;

prefetch

Fetch a given url.

Type Definition
function prefetch(url: string): Promise<void>;
Name Desc
url Url to prefetch

It uses <link rel=prefetch> if possible.

prefetch('https://eustia.ooo9.io/');

prefix

Add vendor prefixes to a CSS attribute.

Type Definition
namespace prefix {
    function dash(name: string): string;
}
function prefix(name: string): string;
Name Desc
name Property name
return Prefixed property name

dash

Create a dasherize version.

prefix('text-emphasis'); // -> 'WebkitTextEmphasis'
prefix.dash('text-emphasis'); // -> '-webkit-text-emphasis'
prefix('color'); // -> 'color'

promisify

Convert callback based functions into Promises.

Type Definition
function promisify(
    fn: types.AnyFn,
    multiArgs?: boolean
): types.AnyFn;
Name Desc
fn Callback based function
multiArgs=false If callback has multiple success value
return Result function

If multiArgs is set to true, the resulting promise will always fulfill with an array of the callback's success values.

const fs = require('fs');

const readFile = promisify(fs.readFile);
readFile('test.js', 'utf-8').then(function(data) {
    // Do something with file content.
});

property

Return a function that will itself return the key property of any passed-in object.

Type Definition
function property(path: string | string[]): types.AnyFn;
Name Desc
path Path of the property to get
return New accessor function
const obj = { a: { b: 1 } };
property('a')(obj); // -> {b: 1}
property(['a', 'b'])(obj); // -> 1

query

Parse and stringify url query strings.

Type Definition
const query: {
    parse(str: string): any;
    stringify(object: any): string;
};

parse

Parse a query string into an object.

Name Desc
str Query string
return Query object

stringify

Stringify an object into a query string.

Name Desc
obj Query object
return Query string
query.parse('foo=bar&eruda=true'); // -> {foo: 'bar', eruda: 'true'}
query.stringify({ foo: 'bar', eruda: 'true' }); // -> 'foo=bar&eruda=true'
query.parse('name=eruda&name=eustia'); // -> {name: ['eruda', 'eustia']}

quickSort

Quick sort implementation.

Type Definition
function quickSort(arr: any[], cmp?: types.AnyFn): any[];
Name Desc
arr Array to sort
cmp Comparator
return Sorted array
quickSort([2, 1]); // -> [1, 2]

raf

Shortcut for requestAnimationFrame.

Type Definition
namespace raf {
    function cancel(id: number): void;
}
function raf(cb: types.AnyFn): number;

Use setTimeout if native requestAnimationFrame is not supported.

const id = raf(function tick() {
    // Animation stuff
    raf(tick);
});
raf.cancel(id);

random

Produces a random number between min and max(inclusive).

Type Definition
function random(
    min: number,
    max?: number,
    floating?: boolean
): number;
Name Desc
min Minimum possible value
max Maximum possible value
floating=false Float or not
return Random number
random(1, 5); // -> an integer between 0 and 5
random(5); // -> an integer between 0 and 5
random(1.2, 5.2, true); /// -> a floating-point number between 1.2 and 5.2

randomBytes

Random bytes generator.

Type Definition
function randomBytes(size: number): Uint8Array;

Use crypto module in node or crypto object in browser if possible.

Name Desc
size Number of bytes to generate
return Random bytes of given length
randomBytes(5); // -> [55, 49, 153, 30, 122]

randomColor

Random color generator.

Type Definition
function randomColor(): string;
function randomColor(options: {
    count?: number;
    hue?: number;
    lightness?: number;
    format?: string;
    seed?: number;
}): string | string[];
Name Desc
options Random options
return Random color

Available options:

Name Desc
count=1 Color number
hue Hue, number between 0 and 360
lightness Lightness, number between 0 and 1
format=hex Color format, hex, hsl or rgb
seed Random color seed
randomColor({
    count: 2
}); // -> ['#fed7f4', '#526498']

randomId

A tiny id generator, similar to nanoid.

Type Definition
function randomId(size?: number, symbols?: string): string;
Name Desc
size=21 Id size
symbols Symbols used to generate ids, a-zA-Z0-9_- by default
randomId(); // -> 'oKpy4HwU8E6IvU5I03gyQ'
randomId(5); // -> 'sM6E9'
randomId(5, 'abc'); // -> 'cbbcb'

randomItem

Get a random item from an array.

Type Definition
function randomItem(arr: any[]): any;
Name Desc
arr Array to get
return Randomly picked item
randomItem([1, 2, 3]); // -> 2

range

Create flexibly-numbered lists of integers.

Type Definition
function range(
    start: number,
    end?: number,
    step?: number
): number[];
Name Desc
start Start of the range
end End of the range
step=1 Value to increment or decrement by
return List of integers
range(5); // -> [0, 1, 2, 3, 4]
range(0, 5, 2); // -> [0, 2, 4]

rc4

RC4 symmetric encryption implementation.

Type Definition
const rc4: {
    encrypt(key: string, str: string): string;
    decrypt(key: string, str: string): string;
};

encrypt

RC4 encryption, result as base64 string.

decrypt

RC4 decryption, pass base64 string as input.

Name Desc
key Secret key
str String to be encrypted/decrypted
return Encrypted/decrypted string
rc4.encrypt('zso', 'Hello world'); // -> 'j9y2VpSfR3AdNN8='
rc4.decrypt('zso', 'j9y2VpSfR3AdNN8='); // -> 'Hello world'

ready

Invoke callback when dom is ready, similar to jQuery ready.

Type Definition
function ready(fn: types.AnyFn): void;
Name Desc
fn Callback function
ready(function() {
    // It's safe to manipulate dom here.
});

reduce

Turn a list of values into a single value.

Type Definition
function reduce<T, TResult>(
    list: types.List<T>,
    iterator: types.MemoIterator<T, TResult>,
    memo?: TResult,
    context?: any
): TResult;
function reduce<T, TResult>(
    list: types.Dictionary<T>,
    iterator: types.MemoObjectIterator<T, TResult>,
    memo?: TResult,
    context?: any
): TResult;
Name Desc
obj Collection to iterate over
iterator=identity Function invoked per iteration
initial Initial value
ctx Function context
return Accumulated value
reduce(
    [1, 2, 3],
    function(sum, n) {
        return sum + n;
    },
    0
); // -> 6

reduceRight

Right-associative version of reduce.

Type Definition
function reduceRight<T, TResult>(
    list: types.Collection<T>,
    iterator: types.MemoIterator<T, TResult>,
    memo?: TResult,
    context?: any
): TResult;
reduceRight(
    [[1], [2], [3]],
    function(a, b) {
        return a.concat(b);
    },
    []
); // -> [3, 2, 1]

reject

Opposite of filter.

Type Definition
function reject<T>(
    list: types.List<T>,
    iterator: types.ListIterator<T, boolean>,
    context?: any
): T[];
function reject<T>(
    object: types.Dictionary<T>,
    iterator: types.ObjectIterator<T, boolean>,
    context?: any
): T[];
Name Desc
obj Collection to iterate over
predicate Function invoked per iteration
ctx Predicate context
return Array of all values that didn't pass predicate
reject([1, 2, 3, 4, 5], function(val) {
    return val % 2 === 0;
}); /

Readme

Keywords

Package Sidebar

Install

npm i zso

Weekly Downloads

0

Version

0.5.8

License

MIT

Unpacked Size

860 kB

Total Files

897

Last publish

Collaborators

  • ooo9