Skip to content

$

source test1.0.0

jQuery like style dom manipulator.

Type Definition
typescript
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

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

$attr

source test1.0.0

Element attribute manipulation.

Type Definition
typescript
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.

NameDesc
elementElements to manipulate
nameAttribute name
returnAttribute value of first element

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

NameDesc
elementElements to manipulate
nameAttribute name
valAttribute value
NameDesc
elementElements to manipulate
attributesObject of attribute-value pairs to set

remove

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

NameDesc
elementElements to manipulate
nameAttribute name
javascript
$attr('#test', 'attr1', 'test');
$attr('#test', 'attr1'); // -> test
$attr.remove('#test', 'attr1');
$attr('#test', {
    attr1: 'test',
    attr2: 'test'
});

$class

source test1.0.0

Element class manipulations.

Type Definition
typescript
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.

NameDesc
elementElements to manipulate
namesClasses to add

has

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

NameDesc
elementElements to manipulate
nameClass name
returnTrue 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.

NameDesc
elementElements to manipulate
nameClass name to toggle

remove

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

NameDesc
elementElements to manipulate
nameClass names to remove
javascript
$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

source test1.0.0

Element css manipulation.

Type Definition
typescript
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.

NameDesc
elementElements to manipulate
nameProperty name
returnCss value of first element

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

NameDesc
elementElements to manipulate
nameProperty name
valCss value
NameDesc
elementElements to manipulate
propertiesObject of css-value pairs to set
javascript
$css('#test', {
    color: '#fff',
    background: 'black',
    opacity: 0.5
});
$css('#test', 'display', 'block');
$css('#test', 'color'); // -> #fff

$data

source test1.0.0

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

Type Definition
typescript
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;
javascript
$data('#test', 'attr1', 'eustia');

$event

source test1.0.0

bind events to certain dom elements.

Type Definition
typescript
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;
};
javascript
function clickHandler() {
    // Do something...
}
$event.on('#test', 'click', clickHandler);
$event.off('#test', 'click', clickHandler);

$insert

source test1.0.0

Insert html on different position.

Type Definition
typescript
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.

NameDesc
elementElements to manipulate
contentHtml strings or element
javascript
// <div id="test"><div class="mark"></div></div>
$insert.before('#test', '<div>licia</div>');
// -> <div>licia</div><div id="test"><div class="mark"></div></div>
$insert.after('#test', '<div>licia</div>');
// -> <div id="test"><div class="mark"></div></div><div>licia</div>
$insert.prepend('#test', '<div>licia</div>');
// -> <div id="test"><div>licia</div><div class="mark"></div></div>
$insert.append('#test', '<div>licia</div>');
// -> <div id="test"><div class="mark"></div><div>licia</div></div>

$offset

source test1.0.0

Get the position of the element in document.

Type Definition
typescript
namespace $offset {
    interface IOffset {
        left: number;
        top: number;
        width: number;
        height: number;
    }
}
function $offset(element: $safeEls.El): $offset.IOffset;
NameDesc
elementElements to get offset
returnElement position
javascript
$offset('#test'); // -> {left: 0, top: 0, width: 0, height: 0}

$property

source test1.0.0

Element property html, text, val getter and setter.

Type Definition
typescript
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.

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

$remove

source test1.0.0

Remove the set of matched elements from the DOM.

Type Definition
typescript
function $remove(element: $safeEls.El);
NameDesc
elementElements to delete
javascript
$remove('#test');

$safeEls

source test1.0.0

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

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

$show

source test1.0.0

Show elements.

Type Definition
typescript
function $show(element: $safeEls.El): void;
NameDesc
elementElements to show
javascript
$show('#test');

Benchmark

source test1.30.0

JavaScript Benchmark.

Type Definition
typescript
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

NameDesc
fnCode for speed testing
optionsBenchmark options

Available options:

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

run

Run benchmark, returns a promise.

all

[static] Run some benchmarks.

javascript
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

source test1.0.0

Use Blob when available, otherwise BlobBuilder.

constructor

NameDesc
partsBlob parts
optionsOptions
javascript
const blob = new Blob([]);

BloomFilter

source test1.10.0

Bloom filter implementation.

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

constructor

NameDesc
size=1024Number of buckets
k=3Number of Hash functions

add

Add an element to the filter.

NameDesc
valValue to add

test

Test if an element is in the filter.

NameDesc
valValue to test
returnTrue if probably, false if definitely not
javascript
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

source test1.9.0

Modify object props without caring about letter case.

Type Definition
typescript
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

NameDesc
objTarget object

getKey

Get key with preserved casing.

NameDesc
keyCaseless key
returnObject key

set

Set value.

NameDesc
keyCaseless key
valValue to set

get

Get value.

NameDesc
keyCaseless key
returnValue of given key

remove

Remove value.

NameDesc
keyCaseless key

has

Determine whether target object has given key.

NameDesc
keyCaseless key
returnTrue if has given key
javascript
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

source test demo1.0.0

Create JavaScript class.

Type Definition
typescript
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;
NameDesc
methodsPublic methods
[staticsStatic methods
returnFunction used to create instances
javascript
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

source test1.0.0

Color converter.

Type Definition
typescript
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

NameDesc
colorColor 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.

NameDesc
colorColor string
returnObject containing value and model
javascript
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

source test1.17.0

Object delegation.

Type Definition
typescript
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

NameDesc
hostHost object
targetDelegation target

method

Allow method to be accessed on the host object.

NameDesc
nameHost method name
target=nameTarget method name

getter

Create a getter.

setter

Create a setter.

access

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

javascript
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

source test1.0.0

Flux dispatcher.

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

Related docs

javascript
const dispatcher = new Dispatcher();

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

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

Emitter

source test1.0.0

Event emitter class which provides observer pattern.

Type Definition
typescript
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.

NameDesc
eventEvent name
listenerEvent listener

emit

Emit event.

NameDesc
eventEvent name
...argsArguments passed to listener

removeAllListeners

Remove all listeners.

NameDesc
eventEvent name

mixin

[static] Mixin object class methods.

NameDesc
objObject to mixin
javascript
const event = new Emitter();
event.on('test', function(name) {
    console.log(name);
});
event.emit('test', 'licia'); // Logs out 'licia'.
Emitter.mixin({});

Enum

source test1.0.0

Enum type implementation.

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

constructor

NameDesc
arrArray of strings
NameDesc
objPairs of key and value
javascript
const importance = new Enum([
    'NONE',
    'TRIVIAL',
    'REGULAR',
    'IMPORTANT',
    'CRITICAL'
]);
const val = 1;
if (val === importance.CRITICAL) {
    // Do something.
}

FileBlobStore

source test1.32.0

Binary file storage.

Type Definition
typescript
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.

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

FileStore

source test1.32.0

File storage.

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

constructor

NameDesc
pathFile path to store
dataDefault data
javascript
const store = new FileStore('path/to/file');
store.set('name', 'licia');

HashTable

source test1.13.0

Hash table implementation.

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

constructor

NameDesc
size=32Bucket size

set

Set value.

NameDesc
keyValue key
valValue to set

get

Get value.

NameDesc
keyValue key
returnValue of given key

has

Check if has value.

NameDesc
keyValue key
returnTrue if value exists

delete

Delete value.

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

Heap

source test1.11.0

Heap implementation.

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

size

Heap size.

constructor

NameDesc
cmpComparator

clear

Clear the heap.

add

Add an item to the heap.

NameDesc
itemItem to add
returnCurrent size

poll

Retrieve and remove the root item of the heap.

peek

Same as poll, but does not remove the item.

javascript
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

source test1.31.0

V8 heap snapshot manipulator.

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

constructor

NameDesc
profileProfile to parse

nodes

Parsed nodes.

edges

Parsed edges.

javascript
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

source test1.23.0

Simple internationalization library.

Type Definition
typescript
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

NameDesc
localeLocale code
langsLanguage data

set

Add language or append extra keys to existing language.

NameDesc
localeLocale code
langLanguage data

locale

Set default locale.

NameDesc
localeLocale code

t

Get translation text.

NameDesc
pathPath of translation to get
dataData to pass in
returnTranslation text
javascript
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: 'licia' }); // -> 'Hello, licia!'
i18n.locale('cn');
i18n.t('curTime', { time: '5:47 pm' }); // -> '当前时间是 5:47 pm'

JsonTransformer

source test1.0.0

Json to json transformer.

Type Definition
typescript
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

NameDesc
data={}Json object to manipulate

set

Set object value.

NameDesc
keyObject key
valValue to set

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

get

Get object value.

NameDesc
keyObject key
returnSpecified value or whole object

remove

Remove object value.

NameDesc
keyObject keys to remove

map

Shortcut for array map.

NameDesc
fromFrom object path
toTarget object path
fnFunction invoked per iteration

filter

Shortcut for array filter.

compute

Compute value from several object values.

NameDesc
fromSource values
toTarget object path
fnFunction to compute target value
javascript
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: 'RedHoodSu', count: 1}

LinkedList

source test1.0.0

Doubly-linked list implementation.

Type Definition
typescript
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.

First node.

tail

Last node.

push

Add an value to the end of the list.

NameDesc
valValue to push
returnCurrent 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.

NameDesc
fnFunction invoked per iteration
returnFirst value that passes predicate

forEach

Iterate over the list.

toArr

Convert the list to a JavaScript array.

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

LocalStore

source test1.0.0

LocalStorage wrapper.

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

Extend from Store.

constructor

NameDesc
nameLocalStorage item name
dataDefault data
javascript
const store = new LocalStore('licia');
store.set('name', 'licia');

Logger

source test demo1.0.0

Simple logger with level filter.

Type Definition
typescript
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

NameDesc
nameLogger name
level=DEBUGLogger level

setLevel

Set level.

NameDesc
levelLogger level

getLevel

Get current level.

trace, debug, info, warn, error

Logging methods.

Log Levels

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

javascript
const logger = new Logger('licia', 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

source test1.4.5

Simple LRU cache.

Type Definition
typescript
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

NameDesc
maxMax items in cache

has

Check if has cache.

NameDesc
keyCache key
returnTrue if value exists

remove

Remove cache.

NameDesc
keyCache key

get

Get cache value.

NameDesc
keyCache key
returnCache value

set

Set cache.

NameDesc
keyCache key
valCache value

clear

Clear cache.

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

MediaQuery

source test demo1.5.2

CSS media query listener.

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

Extend from Emitter.

constructor

NameDesc
queryMedia query

setQuery

Update query.

isMatch

Return true if given media query matches.

Events

match

Triggered when a media query matches.

unmatch

Opposite of match.

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

MutationObserver

source test1.0.0

Safe MutationObserver, does nothing if MutationObserver is not supported.

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

PriorityQueue

source test1.11.0

Priority queue implementation.

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

size

Queue size.

constructor

NameDesc
cmpComparator

clear

Clear the queue.

enqueue

Add an item to the queue.

NameDesc
itemItem to add
returnCurrent size

dequeue

Retrieve and remove the highest priority item of the queue.

peek

Same as dequeue, but does not remove the item.

javascript
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

source test demo1.0.0

Lightweight Promise implementation.

Promises spec

javascript
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

source test1.0.0

Like es6 Map, without iterators.

Type Definition
typescript
const PseudoMap: typeof Map;

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

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

Queue

source test1.0.0

Queue data structure.

Type Definition
typescript
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.

NameDesc
itemItem to enqueue
returnCurrent size

dequeue

Remove the first item of the queue.

peek

Get the first item without removing it.

forEach

Iterate over the queue.

NameDesc
iteratorFunction invoked iteration
ctxFunction context

toArr

Convert queue to a JavaScript array.

javascript
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

source test benchmark1.4.5

LRU implementation without linked list.

Type Definition
typescript
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.

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

Readiness

source test1.32.0

Readiness manager.

Type Definition
typescript
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.

NameDesc
tasksReady tasks

ready

Register ready callback.

NameDesc
tasksTasks to listen
fnCallback to trigger if tasks are ready
returnPromise that will be resolved when ready

isReady

Check if tasks are ready.

NameDesc
tasksTasks to check
returnTrue if all tasks are ready
javascript
const readiness = new Readiness();
readiness.ready('serverCreated', function() {
    // Do something.
});
readiness.signal('serverCreated');
readiness.isReady('serverCreated'); // -> true

ReduceStore

source test1.0.0

Simplified redux like state container.

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

constructor

NameDesc
reducerFunction returns next state
initialStateInitial state

subscribe

Add a change listener.

NameDesc
listenerCallback to invoke on every dispatch
returnFunction to unsubscribe

dispatch

Dispatch an action.

NameDesc
actionObject representing changes
returnSame action object

getState

Get the current state.

javascript
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

source test demo1.29.0

Detect if element's size has changed.

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

constructor

NameDesc
elementElement to monitor size

destroy

Stop monitoring resize event.

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

Select

source test1.0.0

Simple wrapper of querySelectorAll to make dom selection easier.

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

constructor

NameDesc
selectorDom selector string

find

Get desdendants of current matched elements.

NameDesc
selectorDom selector string

each

Iterate over matched elements.

NameDesc
fnFunction to execute for each element
javascript
const $test = new Select('#test');
$test.find('.test').each(function(idx, element) {
    // Manipulate dom nodes
});

Semaphore

source test1.20.0

Limit simultaneous access to a resource.

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

constructor

NameDesc
counter=1Initial counter

wait

Wait to execute until counter is bigger than 0.

NameDesc
fnFunction to execute

signal

Wake up one waiter if any.

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

SessionStore

source test1.0.0

SessionStorage wrapper.

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

Extend from Store.

constructor

NameDesc
nameSessionStorage item name
dataDefault data
javascript
const store = new SessionStore('licia');
store.set('name', 'licia');

SingleEmitter

source test1.29.0

Event emitter with single event type.

Type Definition
typescript
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.

NameDesc
listenerEvent listener

rmAllListeners

Remove all listeners.

emit

Call listeners.

NameDesc
...argsArguments passed to listener

mixin

[static] Mixin object class methods.

NameDesc
objObject to mixin
javascript
const event = new SingleEmitter();
event.addListener(function(name) {
    console.log(name);
});
event.emit('licia'); // Logs out 'licia'.

Socket

source test1.22.0

Tiny WebSocket wrapper.

Type Definition
typescript
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

NameDesc
urlUrl to connect
optionsConnect options

Available options:

NameDesc
protocolsProtocol string
reconnect=trueTry to reconnect if possible

send

Send message.

NameDesc
messageMessage to send

close

Close WebSocket.

NameDesc
codeStatus code
reasonReason of closing

connect

Connect WebSocket, called when initialized.

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

Stack

source test1.0.0

Stack data structure.

Type Definition
typescript
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.

NameDesc
itemItem to add
returnCurrent size

pop

Get the last item of the stack.

peek

Get the last item without removing it.

forEach

Iterate over the stack.

NameDesc
iteratorFunction invoked iteration
ctxFunction context

toArr

Convert the stack to a JavaScript array.

javascript
const stack = new Stack();

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

State

source test1.0.0

Simple state machine.

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

Extend from Emitter.

constructor

NameDesc
initialInitial state
eventsEvents to change state

is

Check current state.

NameDesc
stateState to check
returnTrue if current state equals given value
javascript
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

source test1.0.0

Memory storage.

Type Definition
typescript
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

NameDesc
dataInitial data

set

Set value.

NameDesc
keyValue key
valValue to set

Set values.

NameDesc
valuesKey value pairs

This emit a change event whenever is called.

get

Get value.

NameDesc
keyValue key
returnValue of given key

Get values.

NameDesc
keysArray of keys
returnKey value pairs

remove

Remove value.

NameDesc
keyKey to remove

clear

Clear all data.

each

Iterate over values.

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

Trace

source test1.33.0

Parse, manipulate and generate chrome tracing data.

Type Definition
typescript
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[];
}
javascript
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

source test1.33.0

Easily create chrome tracing data.

Type Definition
typescript
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

NameDesc
optionsTracing options

Available options:

NameDesc
pidProcess id
tidThread id
processNameProcess name
threadNameThread name

start

Start recording.

NameDesc
catEnabled categories

stop

Stop recording and get result events.

begin

Record begin event.

NameDesc
catEvent categories
nameEvent name
argsArguments

end

Record end event.

asyncBegin

Record async begin event.

asyncEnd

Record async end event.

instant

Record instant event.

id

Get an unique id.

javascript
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

source test1.25.0

Trie data structure.

Type Definition
typescript
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.

NameDesc
wordWord to add

remove

Remove a word from trie.

has

Check if word exists.

words

Get all words with given Prefix.

NameDesc
prefixWord prefix
returnWords with given Prefix

clear

Clear all words from trie.

javascript
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

source test demo1.0.0

Tween engine for JavaScript animations.

Type Definition
typescript
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

NameDesc
objValues to tween

to

NameDesc
destinationFinal properties
durationTween duration
easeEasing function

play

Begin playing forward.

pause

Pause the animation.

paused

Get animation paused state.

progress

Update or get animation progress.

NameDesc
progressNumber between 0 and 1
javascript
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

source test1.0.0

Simple url manipulator.

Type Definition
typescript
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

NameDesc
url=locationUrl string

setQuery

Set query value.

NameDesc
nameQuery name
valQuery value
returnthis
NameDesc
queryquery object
returnthis

rmQuery

Remove query value.

NameDesc
nameQuery name
returnthis

parse

[static] Parse url into an object.

NameDesc
urlUrl string
returnUrl object

stringify

[static] Stringify url object into a string.

NameDesc
urlUrl object
returnUrl string

An url object contains the following properties:

NameDesc
protocolThe protocol scheme of the URL (e.g. http:)
slashesA boolean which indicates whether the protocol is followed by two forward slashes (//)
authAuthentication information portion (e.g. username:password)
hostnameHost name without port number
portOptional port number
pathnameURL path
queryParsed object containing query string
hashThe "fragment" portion of the URL including the pound-sign (#)
javascript
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

source test1.0.0

Object values validation.

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

constructor

NameDesc
optionsValidation configuration

validate

Validate object.

NameDesc
objObject to validate
returnValidation result, true means ok

addPlugin

[static] Add plugin.

NameDesc
namePlugin name
pluginValidation handler

Default Plugins

Required, number, boolean, string and regexp.

javascript
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: 'licia' }); // -> true

Wrr

source test1.21.0

Weighted Round Robin implementation.

Type Definition
typescript
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.

NameDesc
valValue to set
weightWeight of the value

get

Get weight of given value.

NameDesc
valValue to get
returnWeight of the value

remove

Remove given value.

NameDesc
valValue to remove

next

Get next value from pool.

clear

Clear all values.

javascript
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

source test1.0.0

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

Type Definition
typescript
function abbrev(...names: string[]): types.PlainObj<string>;
NameDesc
namesList of names
returnAbbreviation map
javascript
abbrev('lina', 'luna');
// -> {li: 'lina', lin: 'lina', lina: 'lina', lu: 'luna', lun: 'luna', luna: 'luna'}

after

source test1.0.0

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

Type Definition
typescript
function after<T extends types.AnyFn>(n: number, fn: T): T;
NameDesc
nNumber of calls before invoked
fnFunction to restrict
returnNew restricted function
javascript
const fn = after(5, function() {
    // -> Only invoke after fn is called 5 times.
});

ajax

source test1.0.0

Perform an asynchronous HTTP request.

Type Definition
typescript
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;
NameDesc
optionsAjax options

Available options:

NameDesc
type=getRequest type
urlRequest url
dataRequest data
dataType=jsonResponse type(json, xml)
contentType=application/x-www-form-urlencodedRequest header Content-Type
successSuccess callback
errorError callback
completeCallback after request
timeoutRequest timeout

get

Shortcut for type = GET;

post

Shortcut for type = POST;

NameDesc
urlRequest url
dataRequest data
successSuccess callback
dataTypeResponse type
javascript
ajax({
    url: 'http://example.com',
    data: { test: 'true' },
    error() {},
    success(data) {
        // ...
    },
    dataType: 'json'
});

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

allKeys

source test1.0.0

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

Type Definition
typescript
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[];
NameDesc
objObject to query
optionsOptions
returnArray of all property names

Available options:

NameDesc
prototype=trueInclude prototype keys
unenumerable=falseInclude unenumerable keys
symbol=falseInclude symbol keys

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

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

ansiColor

source test1.4.1

Ansi colors.

Type Definition
typescript
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

javascript
ansiColor.red('Warning');

arrToMap

source test1.0.0

Make an object map using array of strings.

Type Definition
typescript
function arrToMap<T>(
    arr: string[],
    val?: T
): { [key: string]: T };
NameDesc
arrArray of strings
val=trueKey value
returnObject map
javascript
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

source test1.0.0

Use Buffer to emulate atob when running in node.

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

average

source test1.0.0

Get average value of given numbers.

Type Definition
typescript
function average(...numbers: number[]): number;
NameDesc
numbersNumbers to calculate
returnAverage value
javascript
average(5, 3, 1); // -> 3

base64

source test1.0.0

Basic base64 encoding and decoding.

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

encode

Turn a byte array into a base64 string.

NameDesc
bytesByte array
returnBase64 string

decode

Turn a base64 string into a byte array.

NameDesc
strBase64 string
returnByte array
javascript
base64.encode([168, 174, 155, 255]); // -> 'qK6b/w=='
base64.decode('qK6b/w=='); // -> [168, 174, 155, 255]

before

source test1.0.0

Create a function that invokes less than n times.

Type Definition
typescript
function before<T extends types.AnyFn>(n: number, fn: T): T;
NameDesc
nNumber of calls at which fn is no longer invoked
fnFunction to restrict
returnNew restricted function

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

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

binarySearch

source test1.4.0

Binary search implementation.

Type Definition
typescript
function binarySearch(
    array: any[],
    val: any,
    cmp?: types.AnyFn
): number;
NameDesc
arraySorted array
valValue to seek
cmpComparator
returnValue index
javascript
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

source test1.0.0

Create a function bound to a given object.

Type Definition
typescript
function bind(
    fn: types.AnyFn,
    ctx: any,
    ...args: any[]
): types.AnyFn;
NameDesc
fnFunction to bind
ctxThis binding of given fn
argsOptional arguments
returnNew bound function
javascript
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

source test1.0.0

Use Buffer to emulate btoa when running in node.

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

bubbleSort

source test1.0.0

Bubble sort implementation.

Type Definition
typescript
function bubbleSort(arr: any[], cmp?: types.AnyFn): any[];
NameDesc
arrArray to sort
cmpComparator
returnSorted array
javascript
bubbleSort([2, 1]); // -> [1, 2]

bytesToStr

source test1.1.0

Convert bytes to string.

Type Definition
typescript
function bytesToStr(bytes: number[], encoding?: string): string;
NameDesc
bytesBytes array
encoding=utf8Encoding of string
returnResult string
javascript
bytesToStr([108, 105, 99, 105, 97]); // -> 'licia'

bytesToWords

source test1.16.0

Convert bytes to 32-bit words.

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

Useful when using CryptoJS.

NameDesc
bytesByte array
returnWord array
javascript
bytesToWords([0x12, 0x34, 0x56, 0x78]); // -> [0x12345678]

cacheRequire

source test benchmark1.32.0

Cache everything in module require to speed up app load.

Type Definition
typescript
function cacheRequire(options?: {
    dir?: string;
    requirePath?: boolean;
    code?: boolean;
    compileCache?: boolean;
}): void;
NameDesc
optionsCache options

Available options:

NameDesc
dirCache dir
requirePath=trueWhether require path should be cached
code=falseWhether js code should be cached
compileCache=trueWhether compile cache should be used
javascript
cacheRequire({
    dir: 'path/to/cache/dir'
});

callbackify

source test1.0.0

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

Type Definition
typescript
function callbackify(fn: types.AnyFn): types.AnyFn;
NameDesc
fnFunction that returns a Promise
returnFunction following the error-fist callback style
javascript
function fn() {
    return new Promise(function(resolve, reject) {
        // ...
    });
}

const cbFn = callbackify(fn);

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

camelCase

source test1.0.0

Convert string to "camelCase".

Type Definition
typescript
function camelCase(str: string): string;
NameDesc
strString to convert
returnCamel cased string
javascript
camelCase('foo-bar'); // -> fooBar
camelCase('foo bar'); // -> fooBar
camelCase('foo_bar'); // -> fooBar
camelCase('foo.bar'); // -> fooBar

capitalize

source test1.0.0

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

Type Definition
typescript
function capitalize(str: string): string;
NameDesc
strString to capitalize
returnCapitalized string
javascript
capitalize('rED'); // -> Red

castPath

source test1.0.0

Cast value into a property path array.

Type Definition
typescript
function castPath(path: string | string[], obj?: any): string[];
NameDesc
pathValue to inspect
objObject to query
returnProperty path array
javascript
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

source test1.0.0

Center align text in a string.

Type Definition
typescript
function centerAlign(
    str: string | string[],
    width?: number
): string;
NameDesc
strString to align
widthTotal width of each line
returnCenter aligned string
javascript
centerAlign('test', 8); // -> '  test'
centerAlign('test\nlines', 8); // -> '  test\n lines'
centerAlign(['test', 'lines'], 8); // -> '  test\n lines'

cgroup

source test1.35.0

Read cgroup metrics inside container.

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

char

source test1.0.0

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

Type Definition
typescript
function char(num: number): string;
NameDesc
numInteger to convert
returnString representing corresponding char
javascript
char(65); // -> 'A'
char(97); // -> 'a'

chunk

source test1.0.0

Split array into groups the length of given size.

Type Definition
typescript
function chunk(arr: any[], size?: number): Array<any[]>;
NameDesc
arrArray to process
size=1Length of each chunk
returnChunks of given size
javascript
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

source test1.0.0

Clamp number within the inclusive lower and upper bounds.

Type Definition
typescript
function clamp(n: number, lower: number, upper: number): number;
function clamp(n: number, upper: number): number;
NameDesc
nNumber to clamp
lowerLower bound
upperUpper bound
returnClamped number
javascript
clamp(-10, -5, 5); // -> -5
clamp(10, -5, 5); // -> 5
clamp(2, -5, 5); // -> 2
clamp(10, 5); // -> 5
clamp(2, 5); // -> 2

className

source test1.0.0

Utility for conditionally joining class names.

Type Definition
typescript
function className(...names: any[]): string;
NameDesc
namesClass names
returnJoined class names
javascript
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

source test1.27.0

Output cli help.

Type Definition
typescript
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;
NameDesc
dataHelp data
returnCli help
javascript
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: 'licia',
    usage: '<command> [options]',
    commands: [test]
};

cliHelp(data);
cliHelp(test);

clone

source test1.0.0

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

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

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

NameDesc
valValue to clone
returnCloned value
javascript
clone({ name: 'eustia' }); // -> {name: 'eustia'}

cloneDeep

source test1.0.0

Recursively clone value.

Type Definition
typescript
function cloneDeep<T>(val: T): T;
NameDesc
valValue to clone
returnDeep cloned Value
javascript
const obj = [{ a: 1 }, { a: 2 }];
const obj2 = cloneDeep(obj);
console.log(obj[0] === obj2[1]); // -> false

cmpVersion

source test1.0.0

Compare version strings.

Type Definition
typescript
function cmpVersion(v1: string, v2: string): number;
NameDesc
v1Version to compare
v2Version to compare
returnComparison result
javascript
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

source test1.1.0

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

Type Definition
typescript
function combine(keys: string[], values: any[]): any;
NameDesc
keysKeys to be used
valuesValues to be used
returnCreated object
javascript
combine(['a', 'b', 'c'], [1, 2, 3]); // -> {a: 1, b: 2, c: 3}

compact

source test1.0.0

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

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

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

NameDesc
arrArray to compact
returnNew array of filtered values
javascript
compact([0, 1, false, 2, '', 3]); // -> [1, 2, 3]

compose

source test1.0.0

Compose a list of functions.

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

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

NameDesc
...fnFunctions to compose
returnComposed function
javascript
const welcome = compose(
    function(name) {
        return 'hi: ' + name;
    },
    function(name) {
        return name.toUpperCase() + '!';
    }
);

welcome('licia'); // -> 'hi: LICIA!'

compressImg

source test demo1.0.0

Compress image using canvas.

Type Definition
typescript
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;
NameDesc
fileImage file or url
optionsOptions
cbCallback

Available options:

NameDesc
maxWidthMax width
maxHeightMax height
widthOutput image width
heightOutput image height
mimeTypeMime type
quality=0.8Image 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.

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

concat

source test1.0.0

Concat multiple arrays into a single array.

Type Definition
typescript
function concat(...args: Array<any[]>): any[];
NameDesc
...arrArrays to concat
returnConcatenated array
javascript
concat([1, 2], [3], [4, 5]); // -> [1, 2, 3, 4, 5]

contain

source test1.0.0

Check if the value is present in the list.

Type Definition
typescript
function contain(arr: any[] | {} | string, val: any): boolean;
NameDesc
targetTarget object
valValue to check
returnTrue if value is present in the list
javascript
contain([1, 2, 3], 1); // -> true
contain({ a: 1, b: 2 }, 1); // -> true
contain('abc', 'a'); // -> true

container

source test1.35.0

Get container stats inside container.

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

convertBase

source test1.0.0

Convert base of a number.

Type Definition
typescript
function convertBase(
    num: number | string,
    from: number,
    to: number
): string;
NameDesc
numNumber to convert
fromBase from
toBase to
returnConverted number
javascript
convertBase('10', 2, 10); // -> '2'
convertBase('ff', 16, 2); // -> '11111111'

convertBin

source test1.5.0

Convert binary data type.

Type Definition
typescript
namespace convertBin {
    function blobToArrBuffer(blob: any): Promise<ArrayBuffer>;
}
function convertBin(bin: any, type: string): any;
NameDesc
binBinary data to convert
typeBinary type
returnTarget 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.

NameDesc
blobBlob to convert
returnArrayBuffer promise
javascript
convertBin('qK6b/w==', 'Uint8Array'); // -> [168, 174, 155, 255]
convertBin.blobToArrBuffer(new Blob([])).then(arrBuffer => {
    // Do something...
});

source test1.0.0

Simple api for handling browser cookies.

Type Definition
typescript
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.

NameDesc
keyCookie key
returnCorresponding cookie value

set

Set cookie value.

NameDesc
keyCookie key
valCookie value
optionsCookie options
returnModule cookie

remove

Remove cookie value.

NameDesc
keyCookie key
optionsCookie options
returnModule cookie
javascript
cookie.set('a', '1', { path: '/' });
cookie.get('a'); // -> '1'
cookie.remove('a');

copy

source test demo1.0.0

Copy text to clipboard using document.execCommand.

Type Definition
typescript
function copy(text: string, cb?: types.AnyFn): void;
NameDesc
textText to copy
cbOptional callback
javascript
copy('text', function(err) {
    // Handle errors.
});

crc1

source test1.5.7

CRC1 implementation.

Type Definition
typescript
function crc1(
    input: string | number[],
    previous?: number
): number;
NameDesc
inputData to calculate
previousPrevious CRC1 result
returnCRC1 result
javascript
crc1('1234567890').toString(16); // -> 'd'

crc16

source test1.5.9

CRC16 implementation.

Type Definition
typescript
function crc16(
    input: string | number[],
    previous?: number
): number;
NameDesc
inputData to calculate
previousPrevious CRC16 result
returnCRC16 result
javascript
crc16('1234567890').toString(16); // -> 'c57a'

crc32

source test1.5.9

CRC32 implementation.

Type Definition
typescript
function crc32(
    input: string | number[],
    previous?: number
): number;
NameDesc
inputData to calculate
previousPrevious CRC32 result
returnCRC16 result
javascript
crc32('1234567890').toString(16); // -> '261daee5'

crc8

source test1.5.9

CRC8 implementation.

Type Definition
typescript
function crc8(
    input: string | number[],
    previous?: number
): number;
NameDesc
inputData to calculate
previousPrevious CRC8 result
returnCRC8 result
javascript
crc8('1234567890').toString(16); // -> '52'

create

source test1.16.0

Create new object using given object as prototype.

Type Definition
typescript
function create(proto?: object): any;
NameDesc
protoPrototype of new object
returnCreated object
javascript
const obj = create({ a: 1 });
console.log(obj.a); // -> 1

createAssigner

source test1.0.0

Used to create extend, extendOwn and defaults.

Type Definition
typescript
function createAssigner(
    keysFn: types.AnyFn,
    defaults: boolean
): types.AnyFn;
NameDesc
keysFnFunction to get object keys
defaultsNo override when set to true
returnResult function, extend...

createUrl

source test1.0.0

CreateObjectURL wrapper.

Type Definition
typescript
function createUrl(
    data: any,
    options?: { type?: string }
): string;
NameDesc
dataUrl data
optionsUsed when data is not a File or Blob
returnBlob url
javascript
createUrl('test', { type: 'text/plain' }); // -> Blob url
createUrl(['test', 'test']);
createUrl(new Blob([]));
createUrl(new File(['test'], 'test.txt'));

css

source test1.14.0

Css parser and serializer.

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

Comments will be stripped.

parse

Parse css into js object.

NameDesc
cssCss string
returnParsed js object

stringify

Stringify object into css.

NameDesc
stylesheetObject to stringify
optionsStringify options
returnCss string

Options:

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

cssPriority

source test1.29.0

Calculate and compare priority of css selector/rule.

Type Definition
typescript
namespace cssPriority {
    function compare(p1: number[], p2: number[]): number;
}
function cssPriority(
    selector: string,
    options?: {
        important?: boolean;
        inlineStyle?: boolean;
        position?: number;
    }
): number[];
NameType
selectorCSS selector
optionsRule extra info
returnPriority 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.

NameDesc
p1Priority to compare
p2Priority to compare
returnComparison result
javascript
cssPriority('a.button > i.icon:before', {
    important: true,
    inlineStyle: false,
    position: 100
}); // -> [1, 0, 0, 2, 3, 100]

cssSupports

source test1.0.0

Check if browser supports a given CSS feature.

Type Definition
typescript
function cssSupports(name: string, val?: string): boolean;
NameDesc
nameCss property name
valCss property value
returnTrue if supports
javascript
cssSupports('display', 'flex'); // -> true
cssSupports('display', 'invalid'); // -> false
cssSupports('text-decoration-line', 'underline'); // -> true
cssSupports('grid'); // -> true
cssSupports('invalid'); // -> false

curry

source test1.0.0

Function currying.

Type Definition
typescript
function curry(fn: types.AnyFn): types.AnyFn;
NameDesc
fnFunction to curry
returnNew curried function
javascript
const add = curry(function(a, b) {
    return a + b;
});
const add1 = add(1);
add1(2); // -> 3

dataUrl

source test1.41.0

Parse and stringify data urls.

Type Definition
typescript
const dataUrl: {
    parse(
        dataUrl: string
    ): { data: string; mime: string; charset: string; base64: boolean } | null;
    stringify(
        data: any,
        mime: string,
        options?: { base64?: boolean; charset?: string }
    ): string;
};

parse

Parse a data url.

NameDesc
dataUrlData url string
returnParsed object

stringify

Stringify an object into a data url.

NameDesc
dataData to stringify
mimeMime type
optionsStringify options
returnData url string

options

NameDesc
base64=trueWhether is base64
charsetCharset
javascript
dataUrl.parse('data:,Hello%2C%20World%21'); // -> {data: 'Hello, World!', mime: 'text/plain', charset: '', base64: false}
dataUrl.stringify('Hello, World!', 'text/plain'); // -> 'data:,Hello%2C%20World%21'

dateFormat

source test1.0.0

Simple but extremely useful date format function.

Type Definition
typescript
function dateFormat(
    date: Date,
    mask: string,
    utc?: boolean,
    gmt?: boolean
): string;
function dateFormat(
    mask: string,
    utc?: boolean,
    gmt?: boolean
): string;
NameDesc
date=new DateDate object to format
maskFormat mask
utc=falseUTC or not
gmt=falseGMT or not
returnFormatted duration
MaskDesc
dDay of the month as digits; no leading zero for single-digit days
ddDay of the month as digits; leading zero for single-digit days
dddDay of the week as a three-letter abbreviation
ddddDay of the week as its full name
mMonth as digits; no leading zero for single-digit months
mmMonth as digits; leading zero for single-digit months
mmmMonth as a three-letter abbreviation
mmmmMonth as its full name
yyYear as last two digits; leading zero for years less than 10
yyyyYear represented by four digits
hHours; no leading zero for single-digit hours (12-hour clock)
hhHours; leading zero for single-digit hours (12-hour clock)
HHours; no leading zero for single-digit hours (24-hour clock)
HHHours; leading zero for single-digit hours (24-hour clock)
MMinutes; no leading zero for single-digit minutes
MMMinutes; leading zero for single-digit minutes
sSeconds; no leading zero for single-digit seconds
ssSeconds; leading zero for single-digit seconds
l LMilliseconds. l gives 3 digits. L gives 2 digits
tLowercase, single-character time marker string: a or p
ttLowercase, two-character time marker string: am or pm
TUppercase, single-character time marker string: A or P
TTUppercase, two-character time marker string: AM or PM
ZUS timezone abbreviation, e.g. EST or MDT
oGMT/UTC timezone offset, e.g. -0500 or +0230
SThe date's ordinal suffix (st, nd, rd, or th)
UTC:Must be the first four characters of the mask
javascript
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

source test1.0.0

Return a new debounced version of the passed function.

Type Definition
typescript
function debounce<T extends types.AnyFn>(fn: T, wait: number): T;
NameDesc
fnFunction to debounce
waitNumber of milliseconds to delay
returnNew debounced function
javascript
const calLayout = debounce(function() {}, 300);
// $(window).resize(calLayout);

debug

source test demo1.0.0

A tiny JavaScript debugging utility.

Type Definition
typescript
function debug(name: string): any;
NameDesc
nameNamespace
returnFunction to print decorated log
javascript
const d = debug('test');
d('doing lots of uninteresting work');
d.enabled = false;

deburr

source test1.6.1

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

Type Definition
typescript
function deburr(str: string): string;
NameDesc
strString to deburr
returnDeburred string
javascript
deburr('déjà vu'); // -> 'deja vu'

decodeUriComponent

source test1.0.0

Better decodeURIComponent that does not throw if input is invalid.

Type Definition
typescript
function decodeUriComponent(str: string): string;
NameDesc
strString to decode
returnDecoded string
javascript
decodeUriComponent('%%25%'); // -> '%%%'
decodeUriComponent('%E0%A4%A'); // -> '\xE0\xA4%A'

defaults

source test1.0.0

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

Type Definition
typescript
function defaults(obj: any, ...src: any[]): any;
NameDesc
objDestination object
...srcSources objects
returnDestination object
javascript
defaults({ name: 'RedHood' }, { name: 'Unknown', age: 24 }); // -> {name: 'RedHood', age: 24}

define

source test1.0.0

Define a module, should be used along with use.

Type Definition
typescript
function define(
    name: string,
    requires: string[],
    method: types.AnyFn
): void;
function define(name: string, method: types.AnyFn): void;
NameDesc
nameModule name
requiresDependencies
methodModule body

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

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

defineProp

source test1.0.0

Shortcut for Object.defineProperty(defineProperties).

Type Definition
typescript
function defineProp<T>(
    obj: T,
    prop: string,
    descriptor: PropertyDescriptor
): T;
function defineProp<T>(
    obj: T,
    descriptor: PropertyDescriptorMap
): T;
NameDesc
objObject to define
propProperty path
descriptorProperty descriptor
returnObject itself
NameDesc
objObject to define
propProperty descriptors
returnObject itself
javascript
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

source test1.16.0

Return the first argument that is not undefined.

Type Definition
typescript
function defined(...args: any[]): any;
NameDesc
...argsArguments to check
returnFirst defined argument
javascript
defined(false, 2, void 0, 100); // -> false

delRequireCache

source test1.5.4

Delete node.js require cache.

Type Definition
typescript
function delRequireCache(id: string): void;
NameDesc
idModule name or path
javascript
const licia = require('licia');
licia.a = 5;
delRequireCache('licia');
require('licia').a; // -> undefined

delay

source test1.0.0

Invoke function after certain milliseconds.

Type Definition
typescript
function delay(
    fn: types.AnyFn,
    wait: number,
    ...args: any[]
): void;
NameDesc
fnFunction to delay
waitNumber of milliseconds to delay invocation
...argsArguments to invoke fn with
javascript
delay(
    function(text) {
        console.log(text);
    },
    1000,
    'later'
);
// -> Logs 'later' after one second

delegate

source test1.0.0

Event delegation.

Type Definition
typescript
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.

NameDesc
elParent element
typeEvent type
selectorMatch selector
cbEvent callback

remove

Remove event delegation.

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

deprecate

source test demo1.5.0

Node.js util.deprecate with browser support.

Type Definition
typescript
function deprecate(fn: types.AnyFn, msg: string): types.AnyFn;
NameDesc
fnFunction to be deprecated
msgWarning message
returnDeprecated function
javascript
const fn = () => {};
const obsoleteFn = deprecate(fn, 'obsoleteFn is deprecated.');
obsoleteFn();

detectBrowser

source test1.0.0

Detect browser info using ua.

Type Definition
typescript
function detectBrowser(
    ua?: string
): {
    name: string;
    version: number;
};
NameDesc
ua=navigator.userAgentBrowser userAgent
returnObject containing name and version

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

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

detectMocha

source test1.0.0

Detect if mocha is running.

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

detectOs

source test1.0.0

Detect operating system using ua.

Type Definition
typescript
function detectOs(ua?: string): string;
NameDesc
ua=navigator.userAgentBrowser userAgent
returnOperating system name

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

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

difference

source test1.0.0

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

Type Definition
typescript
function difference(arr: any[], ...args: any[]): any[];
NameDesc
arrArray to inspect
...argsValues to exclude
returnNew array of filtered values
javascript
difference([3, 2, 1], [4, 2]); // -> [3, 1]

dotCase

source test1.0.0

Convert string to "dotCase".

Type Definition
typescript
function dotCase(str: string): string;
NameDesc
strString to convert
returnDot cased string
javascript
dotCase('fooBar'); // -> foo.bar
dotCase('foo bar'); // -> foo.bar

download

source test demo1.0.0

Trigger a file download on client side.

Type Definition
typescript
function download(
    data: Blob | File | string | any[],
    name: string,
    type?: string
): void;
NameDesc
dataData to download
nameFile name
type=text/plainData type
javascript
download('test', 'test.txt');

durationFormat

source test1.18.0

Simple duration format function.

Type Definition
typescript
function durationFormat(duration: number, mask?: string): string;
NameDesc
durationDuration to format, millisecond
mask='hh:mm:ss'Format mask
returnFormatted duration
MaskDesc
dDays
hHours
mMinutes
sSeconds
lMilliseconds
javascript
durationFormat(12345678); // -> '03:25:45'
durationFormat(12345678, 'h:m:s:l'); // -> '3:25:45:678'

each

source test benchmark1.0.0

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

Type Definition
typescript
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>;
NameDesc
objCollection to iterate over
iteratorFunction invoked per iteration
ctxFunction context
javascript
each({ a: 1, b: 2 }, function(val, key) {});

easing

source test1.0.0

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

Type Definition
typescript
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;
};
NameDesc
percentNumber between 0 and 1
returnCalculated number
javascript
easing.linear(0.5); // -> 0.5
easing.inElastic(0.5, 500); // -> 0.03125

emulateTouch

source test demo1.9.0

Emulate touch events on desktop browsers.

Type Definition
typescript
function emulateTouch(el: Element): void;
NameDesc
elTarget element
javascript
const el = document.querySelector('#test');
emulateTouch(el);
el.addEventListener('touchstart', () => {}, false);

endWith

source test1.0.0

Check if string ends with the given target string.

Type Definition
typescript
function endWith(str: string, suffix: string): boolean;
NameDesc
strThe string to search
suffixString suffix
returnTrue if string ends with target
javascript
endWith('ab', 'b'); // -> true

escape

source test1.0.0

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

Type Definition
typescript
function escape(str: string): string;
NameDesc
strString to escape
returnEscaped string
javascript
escape('You & Me'); // -> 'You &amp; Me'

escapeJsStr

source test1.0.0

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

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

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

NameDesc
strString to escape
returnEscaped string
javascript
escapeJsStr('"\n'); // -> '\\"\\\\n'

escapeRegExp

source test1.0.0

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

Type Definition
typescript
function escapeRegExp(str: string): string;
NameDesc
strString to escape
returnEscaped string
javascript
escapeRegExp('[licia]'); // -> '\\[licia\\]'

evalCss

source test1.0.0

Load css into page.

Type Definition
typescript
function evalCss(css: string): HTMLStyleElement;
NameDesc
cssCss code
returnStyle element
javascript
evalCss('body{background:#08c}');

evalJs

source test benchmark1.0.0

Execute js in given context.

Type Definition
typescript
function evalJs(js: string, ctx?: any): void;
NameDesc
jsJavaScript code
ctx=globalContext
javascript
evalJs('5+2'); // -> 7
evalJs('this.a', { a: 2 }); // -> 2

every

source test1.0.0

Check if predicate return truthy for all elements.

Type Definition
typescript
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;
NameDesc
objectCollection to iterate over
iteratorFunction invoked per iteration
contextPredicate context
returnTrue if all elements pass the predicate check
javascript
every([2, 4], function(val) {
    return val % 2 === 0;
}); // -> true

extend

source test1.0.0

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

Type Definition
typescript
function extend(destination: any, ...sources: any[]): any;
NameDesc
destinationDestination object
...sourcesSources objects
returnDestination object
javascript
extend({ name: 'RedHood' }, { age: 24 }); // -> {name: 'RedHood', age: 24}

extendDeep

source test1.0.0

Recursive object extending.

Type Definition
typescript
function extendDeep(destination: any, ...sources: any[]): any;
NameDesc
destinationDestination object
...sourcesSources objects
returnDestination object
javascript
extendDeep(
    {
        name: 'RedHood',
        family: {
            mother: 'Jane',
            father: 'Jack'
        }
    },
    {
        family: {
            brother: 'Bruce'
        }
    }
);
// -> {name: 'RedHood', family: {mother: 'Jane', father: 'Jack', brother: 'Bruce'}}

extendOwn

source test1.0.0

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

Type Definition
typescript
function extendOwn(destination: any, ...sources: any[]): any;
NameDesc
destinationDestination object
...sourcesSources objects
returnDestination object
javascript
extendOwn({ name: 'RedHood' }, { age: 24 }); // -> {name: 'RedHood', age: 24}

extractBlockCmts

source test1.0.0

Extract block comments from source code.

Type Definition
typescript
function extractBlockCmts(str: string): string[];
NameDesc
strString to extract
returnBlock comments
javascript
extractBlockCmts('\/*licia*\/'); // -> ['licia']

extractUrls

source test1.0.0

Extract urls from plain text.

Type Definition
typescript
function extractUrls(str: string): string[];
NameDesc
strText to extract
returnUrl list
javascript
const str =
    '[Official site: http://eustia.liriliri.io](http://eustia.liriliri.io)';
extractUrls(str); // -> ['http://eustia.liriliri.io']

fetch

source test1.0.0

Turn XMLHttpRequest into promise like.

Type Definition
typescript
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.

NameDesc
urlRequest url
optionsRequest options
returnRequest promise
javascript
fetch('test.json', {
    method: 'GET',
    timeout: 3000,
    headers: {},
    body: ''
})
    .then(function(res) {
        return res.json();
    })
    .then(function(data) {
        console.log(data);
    });

fibonacci

source test1.0.0

Calculate fibonacci number.

Type Definition
typescript
function fibonacci(n: number): number;
NameDesc
nIndex of fibonacci sequence
returnExpected fibonacci number
javascript
fibonacci(1); // -> 1
fibonacci(3); // -> 2

fileSize

source test1.0.0

Turn bytes into human readable file size.

Type Definition
typescript
function fileSize(bytes: number): string;
NameDesc
bytesFile bytes
returnReadable file size
javascript
fileSize(5); // -> '5'
fileSize(1500); // -> '1.46K'
fileSize(1500000); // -> '1.43M'
fileSize(1500000000); // -> '1.4G'
fileSize(1500000000000); // -> '1.36T'

fileType

source test1.5.1

Detect file type using magic number.

Type Definition
typescript
function fileType(
    input: Buffer | ArrayBuffer | Uint8Array
):
    | {
          ext: string;
          mime: string;
      }
    | undefined;
NameDesc
inputFile input
returnObject containing ext and mime

Supported file types

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

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

fileUrl

source test1.36.0

Convert a file path to a file URL.

Type Definition
typescript
function fileUrl(path: string): string;
NameDesc
pathFile path
returnFile URL
javascript
fileUrl('c:\\foo\\bar'); // -> 'file:///c:/foo/bar'

fill

source test1.0.0

Fill elements of array with value.

Type Definition
typescript
function fill(
    list: any[],
    val: any,
    start?: number,
    end?: number
): any[];
NameDesc
listArray to fill
valValue to fill array with
start=0Start position
end=arr.lengthEnd position
returnFilled array
javascript
fill([1, 2, 3], '*'); // -> ['*', '*', '*']
fill([1, 2, 3], '*', 1, 2); // -> [1, '*', 3]

filter

source test1.0.0

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

Type Definition
typescript
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[];
NameDesc
objCollection to iterate over
predicateFunction invoked per iteration
ctxPredicate context
returnArray of all values that pass predicate
javascript
filter([1, 2, 3, 4, 5], function(val) {
    return val % 2 === 0;
}); // -> [2, 4]

find

source test1.0.0

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

Type Definition
typescript
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;
NameDesc
objectCollection to iterate over
iteratorFunction invoked per iteration
contextPredicate context
returnFirst value that passes predicate
javascript
find(
    [
        {
            name: 'john',
            age: 24
        },
        {
            name: 'jane',
            age: 23
        }
    ],
    function(val) {
        return val.age === 23;
    }
); // -> {name: 'jane', age: 23}

findIdx

source test1.0.0

Return the first index where the predicate truth test passes.

Type Definition
typescript
function