English 中文

$

source test1.0.0

jQuery like style dom manipulator.

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

Available methods

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

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

$attr

source test1.0.0

Element attribute manipulation.

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

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

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
$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
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
$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
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
$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
function $data(
    element: $safeEls.El,
    name: string,
    value: string
): void;
function $data(
    element: $safeEls.El,
    attributes: types.PlainObj<string>
): void;
function $data(element: $safeEls.El, name: string): string;
$data('#test', 'attr1', 'eustia');

$event

source test1.0.0

bind events to certain dom elements.

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

$insert

source test1.0.0

Insert html on different position.

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

before

Insert content before elements.

after

Insert content after elements.

prepend

Insert content to the beginning of elements.

append

Insert content to the end of elements.

NameDesc
elementElements to manipulate
contentHtml strings or element
// <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
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
$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
namespace $property {
    interface IProperty {
        (element: $safeEls.El, value: string): void;
        (element: $safeEls.El): string;
    }
}
const $property: {
    html: $property.IProperty;
    val: $property.IProperty;
    text: $property.IProperty;
};

html

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

text

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

val

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

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

$remove

source test1.0.0

Remove the set of matched elements from the DOM.

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

$safeEls

source test1.0.0

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

Type Definition
namespace $safeEls {
    type El = Element | Element[] | NodeListOf<Element> | string;
}
function $safeEls(val: $safeEls.El): Element[];
NameDesc
valValue to convert
returnArray of elements
$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
function $show(element: $safeEls.El): void;
NameDesc
elementElements to show
$show('#test');

Benchmark

source test1.30.0

JavaScript Benchmark.

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

constructor

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.

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
const blob = new Blob([]);

BloomFilter

source test1.10.0

Bloom filter implementation.

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

[statics|Static methods | |return |Function used to create instances|

const People = Class({
    initialize: function People(name, age) {
        this.name = name;
        this.age = age;
    },
    introduce: function() {
        return 'I am ' + this.name + ', ' + this.age + ' years old.';
    }
});

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

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

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

Color

source test1.0.0

Color converter.

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

constructor

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

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
class Dispatcher {
    dispatch(payload: any);
    register(cb: types.AnyFn): void;
    waitFor(ids: string[]): void;
    unregister(id: string): void;
    isDispatching(): boolean;
}

Related docs

const dispatcher = new Dispatcher();

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

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

Emitter

source test1.0.0

Event emitter class which provides observer pattern.

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

on

Bind event.

off

Unbind event.

once

Bind event that trigger once.

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
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
class Enum {
    size: number;
    constructor(map: string[] | { [member: string]: any });
    [key: string]: any;
}

constructor

NameDesc
arrArray of strings
NameDesc
objPairs of key and value
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
class FileBlobStore extends Emitter {
    constructor(path: string, data?: types.PlainObj<Buffer>);
    set(key: string, buf: Buffer): void;
    set(values: types.PlainObj<Buffer>): void;
    get(key: string): Buffer | void;
    get(keys: string[]): types.PlainObj<Buffer>;
    remove(key: string): void;
    remove(keys: string[]): void;
    clear(): void;
    each(fn: (val: Buffer, key: string) => void): void;
    save(): void;
}

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

save

Save data to disk.

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

FileStore

source test1.32.0

File storage.

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

constructor

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

HashTable

source test1.13.0

Hash table implementation.

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

constructor

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.

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

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
class HeapSnapshot {
    nodes: LinkedList;
    edges: LinkedList;
    constructor(profile: any);
}

constructor

NameDesc
profileProfile to parse

nodes

Parsed nodes.

edges

Parsed edges.

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

I18n

source test1.23.0

Simple internationalization library.

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

constructor

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

size

List size.

head.

First node.

tail

Last node.

push

Add an value to the end of the list.

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.

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

LocalStore

source test1.0.0

LocalStorage wrapper.

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

Extend from Store.

constructor

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

Logger

source test demo1.0.0

Simple logger with level filter.

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

constructor

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.

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

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

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.

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

PriorityQueue

source test1.11.0

Priority queue implementation.

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

size

Queue size.

constructor

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.

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

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
const PseudoMap: typeof Map;

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

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

Queue

source test1.0.0

Queue data structure.

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

size

Queue size.

clear

Clear the queue.

enqueue

Add an item to the queue.

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.

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
class QuickLru {
    constructor(max: number);
    has(key: string): boolean;
    remove(key: string): void;
    get(key: string): any;
    set(key: string, val: any): void;
    clear(): void;
}

Inspired by the hashlru algorithm.

The api is the same as Lru module.

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

Readiness

source test1.32.0

Readiness manager.

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

signal

Signal task is ready.

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

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
class ResizeSensor extends SingleEmitter {
    constructor(el: HTMLElement);
    destroy(): void;
}

constructor

NameDesc
elementElement to monitor size

destroy

Stop monitoring resize event.

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

Select

source test1.0.0

Simple wrapper of querySelectorAll to make dom selection easier.

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

constructor

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

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
class SessionStore extends Store {
    constructor(name: string, data?: any);
}

Extend from Store.

constructor

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

SingleEmitter

source test1.29.0

Event emitter with single event type.

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

addListener

Add listener.

rmListener

Remove listener.

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

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

Stack

source test1.0.0

Stack data structure.

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

size

Stack size.

clear

Clear the stack.

push

Add an item to the stack.

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.

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

Tracing

source test1.33.0

Easily create chrome tracing data.

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

constructor

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.

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

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
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
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
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 (#)
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
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.

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

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
function abbrev(...names: string[]): types.PlainObj<string>;
NameDesc
namesList of names
returnAbbreviation map
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
function after<T extends types.AnyFn>(n: number, fn: T): T;
NameDesc
nNumber of calls before invoked
fnFunction to restrict
returnNew restricted function
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
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
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
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.

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

ansiColor

source test1.4.1

Ansi colors.

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

Available colors

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

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

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

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

ansiColor.red('Warning');

arrToMap

source test1.0.0

Make an object map using array of strings.

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

atob

source test1.0.0

Use Buffer to emulate atob when running in node.

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

average

source test1.0.0

Get average value of given numbers.

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

base64

source test1.0.0

Basic base64 encoding and decoding.

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

encode

Turn a byte array into a base64 string.

NameDesc
bytesByte array
returnBase64 string

decode

Turn a base64 string into a byte array.

NameDesc
strBase64 string
returnByte array
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
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.

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
function binarySearch(
    array: any[],
    val: any,
    cmp?: types.AnyFn
): number;
NameDesc
arraySorted array
valValue to seek
cmpComparator
returnValue index
binarySearch([1, 2, 3], 2); // -> 1
binarySearch([1, 2], 3); // -> -1
binarySearch(
    [
        {
            key: 1
        },
        {
            key: 2
        }
    ],
    { key: 1 },
    (a, b) => {
        if (a.key === b.key) return 0;
        return a.key < b.key ? -1 : 1;
    }
); // -> 0

bind

source test1.0.0

Create a function bound to a given object.

Type Definition
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
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
function btoa(str: string): string;
btoa('Hello World'); // -> 'SGVsbG8gV29ybGQ='

bubbleSort

source test1.0.0

Bubble sort implementation.

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

bytesToStr

source test1.1.0

Convert bytes to string.

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

bytesToWords

source test1.16.0

Convert bytes to 32-bit words.

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

Useful when using CryptoJS.

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

cacheRequire

source test benchmark1.32.0

Cache everything in module require to speed up app load.

Type Definition
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
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
function callbackify(fn: types.AnyFn): types.AnyFn;
NameDesc
fnFunction that returns a Promise
returnFunction following the error-fist callback style
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
function camelCase(str: string): string;
NameDesc
strString to convert
returnCamel cased string
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
function capitalize(str: string): string;
NameDesc
strString to capitalize
returnCapitalized string
capitalize('rED'); // -> Red

castPath

source test1.0.0

Cast value into a property path array.

Type Definition
function castPath(path: string | string[], obj?: any): string[];
NameDesc
pathValue to inspect
objObject to query
returnProperty path array
castPath('a.b.c'); // -> ['a', 'b', 'c']
castPath(['a']); // -> ['a']
castPath('a[0].b'); // -> ['a', '0', 'b']
castPath('a.b.c', { 'a.b.c': true }); // -> ['a.b.c']

centerAlign

source test1.0.0

Center align text in a string.

Type Definition
function centerAlign(
    str: string | string[],
    width?: number
): string;
NameDesc
strString to align
widthTotal width of each line
returnCenter aligned string
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
const cgroup: {
    cpu: {
        stat(): {
            usage: number;
        };
        max(): number;
    };
    cpuset: {
        cpus(): {
            effective: number[];
        };
    };
    memory: {
        max(): number;
        current(): number;
    };
    version(): number;
};
cgroup.cpu.stat();

char

source test1.0.0

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

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

chunk

source test1.0.0

Split array into groups the length of given size.

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

clamp

source test1.0.0

Clamp number within the inclusive lower and upper bounds.

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

className

source test1.0.0

Utility for conditionally joining class names.

Type Definition
function className(...names: any[]): string;
NameDesc
namesClass names
returnJoined class names
className('a', 'b', 'c'); // -> 'a b c'
className('a', false, 'b', 0, 1, 'c'); // -> 'a b 1 c'
className('a', ['b', 'c']); // -> 'a b c'
className('a', { b: false, c: true }); // -> 'a c'
className('a', ['b', 'c', { d: true, e: false }]); // -> 'a b c d';

cliHelp

source test1.27.0

Output cli help.

Type Definition
namespace cliHelp {
    interface IOption {
        name: string;
        shorthand?: string;
        desc: string;
    }
    interface ICommand {
        name: string;
        desc: string;
        usage: string | string[];
        options?: IOption[];
    }
    interface IData {
        name: string;
        usage: string | string[];
        commands: ICommand[];
    }
}
function cliHelp(data: cliHelp.IData | cliHelp.ICommand): string;
NameDesc
dataHelp data
returnCli help
const test = {
    name: 'test',
    desc: 'Generate test files',
    usage: ['<module-name> [options]', 'lpad --browser'],
    options: [
        {
            name: 'browser',
            shorthand: 'b',
            desc: 'True if test should run in a browser'
        }
    ]
};
const data = {
    name: '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
function clone<T>(val: T): T;

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

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

cloneDeep

source test1.0.0

Recursively clone value.

Type Definition
function cloneDeep<T>(val: T): T;
NameDesc
valValue to clone
returnDeep cloned Value
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
function cmpVersion(v1: string, v2: string): number;
NameDesc
v1Version to compare
v2Version to compare
returnComparison result
cmpVersion('1.1.8', '1.0.4'); // -> 1
cmpVersion('1.0.2', '1.0.2'); // -> 0
cmpVersion('2.0', '2.0.0'); // -> 0
cmpVersion('3.0.1', '3.0.0.2'); // -> 1
cmpVersion('1.1.1', '1.2.3'); // -> -1

combine

source test1.1.0

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

Type Definition
function combine(keys: string[], values: any[]): any;
NameDesc
keysKeys to be used
valuesValues to be used
returnCreated object
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
function compact(arr: any[]): any[];

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

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

compose

source test1.0.0

Compose a list of functions.

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

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

NameDesc
...fnFunctions to compose
returnComposed function
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
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.

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
function concat(...args: Array<any[]>): any[];
NameDesc
...arrArrays to concat
returnConcatenated array
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
function contain(arr: any[] | {} | string, val: any): boolean;
NameDesc
targetTarget object
valValue to check
returnTrue if value is present in the list
contain([1, 2, 3], 1); // -> true
contain({ a: 1, b: 2 }, 1); // -> true
contain('abc', 'a'); // -> true

container

source test1.35.0

Get container stats inside container.

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

convertBase

source test1.0.0

Convert base of a number.

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

convertBin

source test1.5.0

Convert binary data type.

Type Definition
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
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
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
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
function copy(text: string, cb?: types.AnyFn): void;
NameDesc
textText to copy
cbOptional callback
copy('text', function(err) {
    // Handle errors.
});

crc1

source test1.5.7

CRC1 implementation.

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

crc16

source test1.5.9

CRC16 implementation.

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

crc32

source test1.5.9

CRC32 implementation.

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

crc8

source test1.5.9

CRC8 implementation.

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

create

source test1.16.0

Create new object using given object as prototype.

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

createAssigner

source test1.0.0

Used to create extend, extendOwn and defaults.

Type Definition
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
function createUrl(
    data: any,
    options?: { type?: string }
): string;
NameDesc
dataUrl data
optionsUsed when data is not a File or Blob
returnBlob url
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
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
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
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
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
function cssSupports(name: string, val?: string): boolean;
NameDesc
nameCss property name
valCss property value
returnTrue if supports
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
function curry(fn: types.AnyFn): types.AnyFn;
NameDesc
fnFunction to curry
returnNew curried function
const add = curry(function(a, b) {
    return a + b;
});
const add1 = add(1);
add1(2); // -> 3

dateFormat

source test1.0.0

Simple but extremely useful date format function.

Type Definition
function dateFormat(
    date: Date,
    mask: string,
    utc?: boolean,
    gmt?: boolean
): string;
function dateFormat(
    mask: string,
    utc?: boolean,
    gmt?: boolean
): string;
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
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
function debounce<T extends types.AnyFn>(fn: T, wait: number): T;
NameDesc
fnFunction to debounce
waitNumber of milliseconds to delay
returnNew debounced function
const calLayout = debounce(function() {}, 300);
// $(window).resize(calLayout);

debug

source test demo1.0.0

A tiny JavaScript debugging utility.

Type Definition
function debug(name: string): any;
NameDesc
nameNamespace
returnFunction to print decorated log
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
function deburr(str: string): string;
NameDesc
strString to deburr
returnDeburred string
deburr('déjà vu'); // -> 'deja vu'

decodeUriComponent

source test1.0.0

Better decodeURIComponent that does not throw if input is invalid.

Type Definition
function decodeUriComponent(str: string): string;
NameDesc
strString to decode
returnDecoded string
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
function defaults(obj: any, ...src: any[]): any;
NameDesc
objDestination object
...srcSources objects
returnDestination object
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
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.

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
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
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
function defined(...args: any[]): any;
NameDesc
...argsArguments to check
returnFirst defined argument
defined(false, 2, void 0, 100); // -> false

delRequireCache

source test1.5.4

Delete node.js require cache.

Type Definition
function delRequireCache(id: string): void;
NameDesc
idModule name or path
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
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
delay(
    function(text) {
        console.log(text);
    },
    1000,
    'later'
);
// -> Logs 'later' after one second

delegate

source test1.0.0

Event delegation.

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

add

Add event delegation.

NameDesc
elParent element
typeEvent type
selectorMatch selector
cbEvent callback

remove

Remove event delegation.

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

deprecate

source test demo1.5.0

Node.js util.deprecate with browser support.

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

detectBrowser

source test1.0.0

Detect browser info using ua.

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

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
function detectMocha(): boolean;
detectMocha(); // -> True if mocha is running.

detectOs

source test1.0.0

Detect operating system using ua.

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

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

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
function difference(arr: any[], ...args: any[]): any[];
NameDesc
arrArray to inspect
...argsValues to exclude
returnNew array of filtered values
difference([3, 2, 1], [4, 2]); // -> [3, 1]

dotCase

source test1.0.0

Convert string to "dotCase".

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

download

source test demo1.0.0

Trigger a file download on client side.

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

durationFormat

source test1.18.0

Simple duration format function.

Type Definition
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
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
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
each({ a: 1, b: 2 }, function(val, key) {});

easing

source test1.0.0

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

Type Definition
const easing: {
    linear(percent: number): number;
    inQuad(percent: number): number;
    outQuad(percent: number): number;
    inOutQuad(percent: number): number;
    outInQuad(percent: number): number;
    inCubic(percent: number): number;
    outCubic(percent: number): number;
    inQuart(percent: number): number;
    outQuart(percent: number): number;
    inQuint(percent: number): number;
    outQuint(percent: number): number;
    inExpo(percent: number): number;
    outExpo(percent: number): number;
    inSine(percent: number): number;
    outSine(percent: number): number;
    inCirc(percent: number): number;
    outCirc(percent: number): number;
    inElastic(percent: number, elasticity?: number): number;
    outElastic(percent: number, elasticity?: number): number;
    inBack(percent: number): number;
    outBack(percent: number): number;
    inOutBack(percent: number): number;
    outInBack(percent: number): number;
    inBounce(percent: number): number;
    outBounce(percent: number): number;
};
NameDesc
percentNumber between 0 and 1
returnCalculated number
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
function emulateTouch(el: Element): void;
NameDesc
elTarget element
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
function endWith(str: string, suffix: string): boolean;
NameDesc
strThe string to search
suffixString suffix
returnTrue if string ends with target
endWith('ab', 'b'); // -> true

escape

source test1.0.0

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

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

escapeJsStr

source test1.0.0

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

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

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

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

escapeRegExp

source test1.0.0

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

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

evalCss

source test1.0.0

Load css into page.

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

evalJs

source test benchmark1.0.0

Execute js in given context.

Type Definition
function evalJs(js: string, ctx?: any): void;
NameDesc
jsJavaScript code
ctx=globalContext
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
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
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
function extend(destination: any, ...sources: any[]): any;
NameDesc
destinationDestination object
...sourcesSources objects
returnDestination object
extend({ name: 'RedHood' }, { age: 24 }); // -> {name: 'RedHood', age: 24}

extendDeep

source test1.0.0

Recursive object extending.

Type Definition
function extendDeep(destination: any, ...sources: any[]): any;
NameDesc
destinationDestination object
...sourcesSources objects
returnDestination object
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
function extendOwn(destination: any, ...sources: any[]): any;
NameDesc
destinationDestination object
...sourcesSources objects
returnDestination object
extendOwn({ name: 'RedHood' }, { age: 24 }); // -> {name: 'RedHood', age: 24}

extractBlockCmts

source test1.0.0

Extract block comments from source code.

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

extractUrls

source test1.0.0

Extract urls from plain text.

Type Definition
function extractUrls(str: string): string[];
NameDesc
strText to extract
returnUrl list
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
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
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
function fibonacci(n: number): number;
NameDesc
nIndex of fibonacci sequence
returnExpected fibonacci number
fibonacci(1); // -> 1
fibonacci(3); // -> 2

fileSize

source test1.0.0

Turn bytes into human readable file size.

Type Definition
function fileSize(bytes: number): string;
NameDesc
bytesFile bytes
returnReadable file size
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
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

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
function fileUrl(path: string): string;
NameDesc
pathFile path
returnFile URL
fileUrl('c:\\foo\\bar'); // -> 'file:///c:/foo/bar'

fill

source test1.0.0

Fill elements of array with value.

Type Definition
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
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
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
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
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
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
function findIdx(arr: any[], predicate: types.AnyFn): number;
NameDesc
arrArray to search
predicateFunction invoked per iteration
returnIndex of matched element
findIdx(
    [
        {
            name: 'john',
            age: 24
        },
        {
            name: 'jane',
            age: 23
        }
    ],
    function(val) {
        return val.age === 23;
    }
); // -> 1

findKey

source test1.0.0

Return the first key where the predicate truth test passes.

Type Definition
function findKey(
    obj: any,
    predicate: types.AnyFn,
    ctx?: any
): string | void;
NameDesc
objObject to search
predicateFunction invoked per iteration
ctxPredicate context
returnKey of matched element
findKey({ a: 1, b: 2 }, function(val) {
    return val === 1;
}); // -> a

findLastIdx

source test1.0.0

Return the last index where the predicate truth test passes.

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

flatten

source test1.0.0

Recursively flatten an array.

Type Definition
function flatten(arr: any[]): any[];
NameDesc
arrArray to flatten
returnNew flattened array
flatten(['a', ['b', ['c']], 'd', ['e']]); // -> ['a', 'b', 'c', 'd', 'e']

fnArgs

source test1.5.3

Validate function arguments.

Type Definition
function fnArgs(types: string[], args: any): void;
NameDesc
typesArgument types
argsArgument object

It throws an exception when validation failed.

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

fnParams

source test1.0.0

Get a function parameter's names.

Type Definition
function fnParams(fn: types.AnyFn | string): string[];
NameDesc
fnFunction to get parameters
returnNames
fnParams(function(a, b) {}); // -> ['a', 'b']

fnv1a

source test1.10.0

Simple FNV-1a implementation.

Type Definition
function fnv1a(str: string): number;
NameDesc
strString to hash
returnHast result
fnv1a('test'); // -> 2949673445

format

source test1.0.0

Format string in a printf-like format.

Type Definition
function format(str: string, ...values: any[]): string;
NameDesc
strString to format
...valuesValues to replace format specifiers
returnFormatted string

Format Specifiers

SpecifierDesc
%sString
%d, %iInteger
%fFloating point value
%oObject
format('%s_%s', 'foo', 'bar'); // -> 'foo_bar'

fraction

source test1.0.0

Convert number to fraction.

Type Definition
function fraction(num: number): string;
NameDesc
numNumber to convert
returnCorresponding fraction
fraction(1.2); // -> '6/5'

freeze

source test1.0.0

Shortcut for Object.freeze.

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

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

NameDesc
objObject to freeze
returnObject passed in
const a = { b: 1 };
freeze(a);
a.b = 2;
console.log(a); // -> {b: 1}

freezeDeep

source test1.0.0

Recursively use Object.freeze.

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

fs

source test1.0.0

Promised version of node.js fs module.

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

fullscreen

source test demo1.4.0

Fullscreen api wrapper.

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

request

Request fullscreen.

NameDesc
elFullscreen element

exit

Exit fullscreen.

toggle

Toggle fullscreen.

NameDesc
elFullscreen element

isActive

Check Whether fullscreen is active.

getEl

Return Fullscreen element if exists.

isEnabled

Whether you are allowed to enter fullscreen.

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

fuzzySearch

source test1.5.0

Simple fuzzy search.

Type Definition
function fuzzySearch(
    needle: string,
    haystack: any[],
    options?: {
        caseSensitive?: boolean;
        key?: string | string[];
    }
): any[];
NameDesc
needleString to search
haystacksSearch list
optionsSearch options

Available options:

NameDesc
caseSensitive=falseWhether comparisons should be case sensitive
keyObject key path if item is object
fuzzySearch('lic', ['licia', 'll', 'lic']); // -> ['lic', 'licia']
fuzzySearch(
    'alpha-test',
    [
        {
            name: 'alpha-test-1'
        },
        {
            name: 'beta-test'
        }
    ],
    {
        key: 'name'
    }
); // -> [{ name: 'alpha-test-1' }]

gcd

source test1.0.0

Compute the greatest common divisor using Euclid's algorithm.

Type Definition
function gcd(a: number, b: number): number;
NameDesc
aNumber to calculate
bNumber to calculate
returnGreatest common divisor
gcd(121, 44); // -> 11

getPort

source test1.1.0

Get an available TCP port.

Type Definition
function getPort(
    port?: number | number[],
    host?: string
): Promise<number>;
NameDesc
portPreferred ports
hostHost address
returnAvailable port

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

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

getProto

source test1.5.5

Get prototype of an object.

Type Definition
function getProto(obj: any): any;
NameDesc
objTarget object
returnPrototype of given object, null if not exists
const a = {};
getProto(Object.create(a)); // -> a

getUrlParam

source test1.0.0

Get url param.

Type Definition
function getUrlParam(
    name: string,
    url?: string
): string | undefined;
NameDesc
nameParam name
url=locationUrl to get param
returnParam value
getUrlParam('test', 'http://example.com/?test=true'); // -> 'true'

golangify

source test1.5.4

Handle errors like golang.

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

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

h

source test1.5.1

Create html with JavaScript.

Type Definition
function h(
    tag: string,
    attrs?: types.PlainObj<any>,
    ...child: Array<string | HTMLElement>
): HTMLElement;
NameDesc
tagTag name
attrsAttributes
...childChildren
returnCreated element
const el = h(
    'div#test.title',
    {
        onclick: function() {},
        title: 'test'
    },
    'inner text'
);
document.body.appendChild(el);

has

source test1.0.0

Checks if key is a direct property.

Type Definition
function has(obj: {}, key: string): boolean;
NameDesc
objObject to query
keyPath to check
returnTrue if key is a direct property
has({ one: 1 }, 'one'); // -> true

heapSort

source test1.11.0

Heap sort implementation.

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

hex

source test1.15.0

Hex encoding and decoding.

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

encode

Turn a byte array into a hex string.

NameDesc
bytesByte array
returnhex string

decode

Turn a hex string into a byte array.

NameDesc
strhex string
returnByte array
hex.encode([168, 174, 155, 255]); // -> 'a8ae9bff'
hex.decode('a8ae9bff'); // -> [168, 174, 155, 255]

highlight

source test demo1.5.6

Highlight code.

Type Definition
function highlight(
    str: string,
    lang?: string,
    style?: {
        comment?: string;
        string?: string;
        number?: string;
        keyword?: string;
        operator?: string;
    }
): string;
NameDesc
strCode string
lang=jsLanguage, js, html or css
styleKeyword highlight style
returnHighlighted html code string

Available styles:

comment, string, number, keyword, operator

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

hookFn

source test1.34.0

Monitor, change function arguments and result.

Type Definition
function hookFn<T>(
    fn: T,
    options: {
        before?: types.AnyFn;
        after?: types.AnyFn;
        error?: types.AnyFn;
    }
): T;
NameDesc
fnFunction to hook
optionsHook options
returnHooked function

Available options:

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

hotkey

source test demo1.0.0

Capture keyboard input to trigger given events.

Type Definition
namespace hotkey {
    interface IOptions {
        element?: HTMLElement;
    }
}
const hotkey: {
    on(key: string, options: hotkey.IOptions, listener: types.AnyFn): void;
    on(key: string, listener: types.AnyFn): void;
    off(key: string, options: hotkey.IOptions, listener: types.AnyFn): void;
    off(key: string, listener: types.AnyFn): void;
};

on

Register keyboard listener.

NameDesc
keyKey string
optionsHotkey options
listenerKey listener

Options:

NameDesc
element=documentTarget element

off

Unregister keyboard listener.

const container = document.getElementById('container');
hotkey.on(
    'k',
    {
        element: container
    },
    function() {
        console.log('k is pressed');
    }
);
function keyDown() {}
hotkey.on('shift+a, shift+b', keyDown);
hotkey.off('shift+a', keyDown);

hslToRgb

source test1.0.0

Convert hsl to rgb.

Type Definition
function hslToRgb(hsl: number[]): number[];
NameDesc
hslHsl values
returnRgb values
hslToRgb([165, 59, 50, 0.8]); // -> [52, 203, 165, 0.8]

html

source test1.6.0

Html parser and serializer.

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

parse

Parse html string into js object.

NameDesc
htmlHtml string
returnParsed js object

stringify

Stringify object into an html string.

NameDesc
treeObject to stringify
returnHtml string
const tree = html.parse('<div id="name">licia</div>');
// -> [{tag: 'div', attrs: {id: 'name'}, content: ['licia']}]
html.stringify(tree);

identity

source test1.0.0

Return the first argument given.

Type Definition
function identity<T>(val: T): T;
NameDesc
valAny value
returnGiven value
identity('a'); // -> 'a'

idxOf

source test1.0.0

Get the index at which the first occurrence of value.

Type Definition
function idxOf(arr: any[], val: any, fromIdx?: number): number;
NameDesc
arrArray to search
valValue to search for
fromIdx=0Index to search from
returnValue index
idxOf([1, 2, 1, 2], 2, 2); // -> 3

indent

source test1.0.0

Indent each line in a string.

Type Definition
function indent(
    str: string,
    char?: string,
    len?: number
): string;
NameDesc
strString to indent
charCharacter to prepend
lenIndent length
returnIndented string
indent('foo\nbar', ' ', 4); // -> '    foo\n    bar'

inherits

source test1.0.0

Inherit the prototype methods from one constructor into another.

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

ini

source test1.5.4

Ini parser and serializer.

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

parse

Parse ini string into js object.

NameDesc
iniIni string
returnParsed js object

stringify

Stringify object into an ini formatted string.

NameDesc
objObject to stringify
optionsStringify options
returnIni formatted string

Options:

NameDesc
sectionTop section
whitespace=falseWhitespace around =
const config = ini.parse(`
; This is a comment
library = licia

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

ini.stringify(config);

insertionSort

source test1.0.0

Insertion sort implementation.

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

intersect

source test1.0.0

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

Type Definition
function intersect(...arr: Array<any[]>): any[];
NameDesc
...arrArrays to inspect
returnNew array of inspecting values
intersect([1, 2, 3, 4], [2, 1, 10], [2, 1]); // -> [1, 2]

intersectRange

source test1.0.0

Intersect two ranges.

Type Definition
namespace intersectRange {
    interface IRange {
        start: number;
        end: number;
    }
}
function intersectRange(
    a: intersectRange.IRange,
    b: intersectRange.IRange
): intersectRange.IRange | void;
NameDesc
aRange a
bRange b
returnIntersection if exist
intersectRange({ start: 0, end: 12 }, { start: 11, end: 13 });
// -> {start: 11, end: 12}
intersectRange({ start: 0, end: 5 }, { start: 6, end: 7 });
// -> undefined

invariant

source test1.17.0

Facebook's invariant.

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

Related docs

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

invert

source test1.0.0

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

Type Definition
function invert(obj: any): any;
NameDesc
objObject to invert
returnNew inverted object

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

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

isAbsoluteUrl

source test1.0.0

Check if an url is absolute.

Type Definition
function isAbsoluteUrl(url: string): boolean;
NameDesc
urlUrl to check
returnTrue if url is absolute
isAbsoluteUrl('http://www.surunzi.com'); // -> true
isAbsoluteUrl('//www.surunzi.com'); // -> false
isAbsoluteUrl('surunzi.com'); // -> false

isArgs

source test1.0.0

Check if value is classified as an arguments object.

Type Definition
function isArgs(val: any): val is IArguments;
NameDesc
valValue to check
returnTrue if value is an arguments object
isArgs(
    (function() {
        return arguments;
    })()
); // -> true

isArr

source test1.0.0

Check if value is an Array object.

Type Definition
function isArr(val: any): val is any[];
NameDesc
valValue to check
returnTrue if value is an Array object
isArr([]); // -> true
isArr({}); // -> false

isArrBuffer

source test1.0.0

Check if value is an ArrayBuffer.

Type Definition
function isArrBuffer(val: any): val is ArrayBuffer;
NameDesc
valValue to check
returnTrue if value is an ArrayBuffer
isArrBuffer(new ArrayBuffer(8)); // -> true

isArrLike

source test1.0.0

Check if value is array-like.

Type Definition
function isArrLike(val: any): boolean;
NameDesc
valValue to check
returnTrue if value is array like

Function returns false.

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

isAsyncFn

source test1.17.0

Check if value is an async function.

Type Definition
function isAsyncFn(val: any): boolean;
NameDesc
valValue to check
returnTrue if value is an async function
isAsyncFn(function*() {}); // -> false
isAsyncFn(function() {}); // -> false
isAsyncFn(async function() {}); // -> true

isBlob

source test1.0.0

Check if value is a Blob.

Type Definition
function isBlob(val: any): boolean;
NameDesc
valValue to check
returnTrue if value is a Blob
isBlob(new Blob([])); // -> true;
isBlob([]); // -> false

isBool

source test1.0.0

Check if value is a boolean primitive.

Type Definition
function isBool(val: any): val is boolean;
NameDesc
valValue to check
returnTrue if value is a boolean
isBool(true); // -> true
isBool(false); // -> true
isBool(1); // -> false

isBrowser

source test1.0.0

Check if running in a browser.

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

isBuffer

source test1.0.0

Check if value is a buffer.

Type Definition
function isBuffer(val: any): boolean;
NameDesc
valThe value to check
returnTrue if value is a buffer
isBuffer(new Buffer(4)); // -> true

isClose

source test1.0.0

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

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

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

NameDesc
aNumber to compare
bNumber to compare
relTol=1e-9Relative tolerance
absTol=0Absolute tolerance
returnTrue if values are close
isClose(1, 1.0000000001); // -> true
isClose(1, 2); // -> false
isClose(1, 1.2, 0.3); // -> true
isClose(1, 1.2, 0.1, 0.3); // -> true

isCyclic

source test benchmark1.30.0

Detect cyclic object reference.

Type Definition
function isCyclic(val: any): boolean;
NameDesc
valValue to detect
returnTrue if value is cyclic
isCyclic({}); // -> false
const obj = { a: 1 };
obj.b = obj;
isCyclic(obj); // -> true

isDarkMode

source test1.19.0

Detect dark mode.

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

isDataUrl

source test1.0.0

Check if a string is a valid data url.

Type Definition
function isDataUrl(str: string): boolean;
NameDesc
strString to check
returnTrue if string is a data url
isDataUrl('http://eustia.liriliri.io'); // -> false
isDataUrl('data:text/plain;base64,SGVsbG8sIFdvcmxkIQ%3D%3D'); // -> true

isDate

source test1.0.0

Check if value is classified as a Date object.

Type Definition
function isDate(val: any): boolean;
NameDesc
valvalue to check
returnTrue if value is a Date object
isDate(new Date()); // -> true

isDir

source test1.28.0

Check if a path is directory.

Type Definition
function isDir(path: string): Promise<boolean>;
NameDesc
pathPath to check
returnTrue if path is a directory
isDir('/foo/bar');

isDocker

source test1.35.0

Check if the process is running inside a docker container.

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

isEl

source test1.0.0

Check if value is a DOM element.

Type Definition
function isEl(val: any): val is Element;
NameDesc
valValue to check
returnTrue if value is a DOM element
isEl(document.body); // -> true

isEmail

source test1.0.0

Loosely validate an email address.

Type Definition
function isEmail(val: string): boolean;
NameDesc
valValue to check
returnTrue if value is an email like string
isEmail('[email protected]'); // -> true

isEmpty

source test1.0.0

Check if value is an empty object or array.

Type Definition
function isEmpty(val: any): boolean;
NameDesc
valValue to check
returnTrue if value is empty
isEmpty([]); // -> true
isEmpty({}); // -> true
isEmpty(''); // -> true

isEqual

source test1.0.0

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

Type Definition
function isEqual(val: any, other: any): boolean;
NameDesc
valValue to compare
otherOther value to compare
returnTrue if values are equivalent
isEqual([1, 2, 3], [1, 2, 3]); // -> true

isErr

source test1.0.0

Check if value is an error.

Type Definition
function isErr(val: any): val is Error;
NameDesc
valValue to check
returnTrue if value is an error
isErr(new Error()); // -> true

isEven

source test1.0.0

Check if number is even.

Type Definition
function isEven(num: number): boolean;
NameDesc
numNumber to check
returnTrue if number is even
isEven(0); // -> true
isEven(1); // -> false
isEven(2); // -> true

isFile

source test1.0.0

Check if value is a file.

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

isFinite

source test1.0.0

Check if value is a finite primitive number.

Type Definition
function isFinite(val: any): boolean;
NameDesc
valValue to check
returnTrue if value is a finite number
isFinite(3); // -> true
isFinite(Infinity); // -> false

isFn

source test1.0.0

Check if value is a function.

Type Definition
function isFn(val: any): val is Function;
NameDesc
valValue to check
returnTrue if value is a function

Generator function is also classified as true.

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

isFullWidth

source test1.24.0

Check if character is full width.

Type Definition
function isFullWidth(codePoint: number): boolean;
NameDesc
codePointUnicode code point
returnTrue if character is full width
isFullWidth('a'.codePointAt(0)); // -> false
isFullWidth(','.codePointAt(0)); // -> false
isFullWidth('我'.codePointAt(0)); // -> true
isFullWidth(','.codePointAt(0)); // -> true

isGeneratorFn

source test1.0.0

Check if value is a generator function.

Type Definition
function isGeneratorFn(val: any): boolean;
NameDesc
valValue to check
returnTrue if value is a generator function
isGeneratorFn(function*() {}); // -> true
isGeneratorFn(function() {}); // -> false

isHidden

source test1.18.0

Check if element is hidden.

Type Definition
function isHidden(
    el: Element,
    options?: {
        display?: boolean;
        visibility?: boolean;
        opacity?: boolean;
        size?: boolean;
        viewport?: boolean;
        overflow?: boolean;
    }
): boolean;
NameDesc
elTarget element
optionsCheck options
returnTrue if element is hidden

Available options:

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

isInt

source test1.0.0

Checks if value is classified as a Integer.

Type Definition
function isInt(val: any): boolean;
NameDesc
valValue to check
returnTrue if value is correctly classified
isInt(5); // -> true
isInt(5.1); // -> false
isInt({}); // -> false

isIp

source test1.5.1

Check if value is an IP address.

Type Definition
namespace isIp {
    function v4(str: string): boolean;
    function v6(str: string): boolean;
}
function isIp(str: string): boolean;
NameDesc
strString to check
returnTrue if value is an IP address

v4

Check if value is an IPv4 address.

v6

Check if value is an IPv6 address.

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

isJson

source test1.0.0

Check if value is a valid JSON.

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

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

NameDesc
valJSON string
returnTrue if value is a valid JSON
isJson('{"a": 5}'); // -> true
isJson("{'a': 5}"); // -> false

isLeapYear

source test1.0.0

Check if a year is a leap year.

Type Definition
function isLeapYear(year: number): boolean;
NameDesc
yearYear to check
returnTrue if year is a leap year
isLeapYear(2000); // -> true
isLeapYear(2002); // -> false

isMap

source test1.0.0

Check if value is a Map object.

Type Definition
function isMap(val: any): boolean;
NameDesc
valValue to check
returnTrue if value is a Map
isMap(new Map()); // -> true
isMap(new WeakMap()); // -> false

isMatch

source test1.0.0

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

Type Definition
function isMatch(obj: any, src: any): boolean;
NameDesc
objObject to inspect
srcObject of property values to match
returnTrue if object is match
isMatch({ a: 1, b: 2 }, { a: 1 }); // -> true

isMiniProgram

source test1.0.0

Check if running in wechat mini program.

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

isMobile

source test1.0.0

Check whether client is using a mobile browser using ua.

Type Definition
function isMobile(ua?: string): boolean;
NameDesc
ua=navigator.userAgentUser agent
returnTrue if ua belongs to mobile browsers
isMobile(navigator.userAgent);

isNaN

source test1.0.0

Check if value is an NaN.

Type Definition
function isNaN(val: any): boolean;
NameDesc
valValue to check
returnTrue if value is an NaN

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

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

isNative

source test1.0.0

Check if value is a native function.

Type Definition
function isNative(val: any): boolean;
NameDesc
valValue to check
returnTrue if value is a native function
isNative(function() {}); // -> false
isNative(Math.min); // -> true

isNil

source test1.0.0

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

Type Definition
function isNil(val: any): boolean;
NameDesc
valValue to check
returnTrue if value is null or undefined
isNil(null); // -> true
isNil(void 0); // -> true
isNil(undefined); // -> true
isNil(false); // -> false
isNil(0); // -> false
isNil([]); // -> false

isNode

source test1.0.0

Check if running in node.

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

isNull

source test1.0.0

Check if value is an Null.

Type Definition
function isNull(val: any): val is null;
NameDesc
valValue to check
returnTrue if value is an Null
isNull(null); // -> true

isNum

source test1.0.0

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

Type Definition
function isNum(val: any): val is number;
NameDesc
valValue to check
returnTrue if value is correctly classified
isNum(5); // -> true
isNum(5.1); // -> true
isNum({}); // -> false

isNumeric

source test1.0.0

Check if value is numeric.

Type Definition
function isNumeric(val: any): boolean;
NameDesc
valValue to check
returnTrue if value is numeric
isNumeric(1); // -> true
isNumeric('1'); // -> true
isNumeric(Number.MAX_VALUE); // -> true
isNumeric(0xff); // -> true
isNumeric(''); // -> false
isNumeric('1.1.1'); // -> false
isNumeric(NaN); // -> false

isObj

source test1.0.0

Check if value is the language type of Object.

Type Definition
function isObj(val: any): boolean;
NameDesc
valValue to check
returnTrue if value is an object

Language Spec

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

isOdd

source test1.0.0

Check if number is odd.

Type Definition
function isOdd(num: number): boolean;
NameDesc
numNumber to check
returnTrue if number is odd
isOdd(0); // -> false
isOdd(1); // -> true
isOdd(2); // -> false

isPlainObj

source test1.0.0

Check if value is an object created by Object constructor.

Type Definition
function isPlainObj(val: any): boolean;
NameDesc
valValue to check
returnTrue if value is a plain object
isPlainObj({}); // -> true
isPlainObj([]); // -> false
isPlainObj(function() {}); // -> false

isPortFree

source test1.5.2

Check if a TCP port is free.

Type Definition
function isPortFree(
    port: number,
    host?: string
): Promise<boolean>;
NameDesc
portTCP port
hostHost address
returnTrue if given port is free
isPortFree(3000).then(isFree => {
    // Do something.
});

isPrime

source test1.2.0

Check if the provided integer is a prime number.

Type Definition
function isPrime(num: number): boolean;
NameDesc
numNumber to check
returnTrue if number is a prime number
isPrime(11); // -> true
isPrime(8); // -> false

isPrimitive

source test1.0.0

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

Type Definition
function isPrimitive(val: any): boolean;
NameDesc
valValue to check
returnTrue if value is a primitive
isPrimitive(5); // -> true
isPrimitive('abc'); // -> true
isPrimitive(false); // -> true

isPromise

source test1.0.0

Check if value looks like a promise.

Type Definition
function isPromise(val: any): boolean;
NameDesc
valValue to check
returnTrue if value looks like a promise
isPromise(new Promise(function() {})); // -> true
isPromise({}); // -> false

isRegExp

source test1.0.0

Check if value is a regular expression.

Type Definition
function isRegExp(val: any): val is RegExp;
NameDesc
valValue to check
returnTrue if value is a regular expression
isRegExp(/a/); // -> true

isRelative

source test1.0.0

Check if path appears to be relative.

Type Definition
function isRelative(path: string): boolean;
NameDesc
pathPath to check
returnTrue if path appears to be relative
isRelative('README.md'); // -> true

isRetina

source test1.0.0

Determine if running on a high DPR device or not.

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

isRunning

source test1.22.0

Check if process is running.

Type Definition
function isRunning(pid: number): boolean;
NameDesc
pidProcess id
returnTrue if process is running
isRunning(123456); // true if running

isSet

source test1.0.0

Check if value is a Set object.

Type Definition
function isSet(val: any): boolean;
NameDesc
valValue to check
returnTrue if value is a Set
isSet(new Set()); // -> true
isSet(new WeakSet()); // -> false

isSorted

source test1.0.0

Check if an array is sorted.

Type Definition
function isSorted(arr: any[], cmp?: types.AnyFn): boolean;
NameDesc
arrArray to check
cmpComparator
returnTrue if array is sorted
isSorted([1, 2, 3]); // -> true
isSorted([3, 2, 1]); // -> false

isStr

source test1.0.0

Check if value is a string primitive.

Type Definition
function isStr(val: any): val is string;
NameDesc
valValue to check
returnTrue if value is a string primitive
isStr('licia'); // -> true

isStrBlank

source test benchmark1.39.0

Check if string is blank.

Type Definition
function isStrBlank(str: string): boolean;
NameDesc
strString to check
returnTrue if string is blank
isStrBlank('licia'); // -> false
isStrBlank(''); // -> true
isStrBlank('    '); // -> true
isStrBlank('\r\n '); // -> true

isStream

source test1.0.0

Check if value is a Node.js stream.

Type Definition
function isStream(val: any): boolean;
NameDesc
valValue to check
returnTrue if value is a Node.js stream
const stream = require('stream');

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

isSymbol

source test1.5.5

Check if value is a symbol.

Type Definition
function isSymbol(val: any): val is symbol;
NameDesc
valValue to check
returnTrue if value is a symbol
isSymbol(Symbol('test')); // -> true

isTypedArr

source test1.0.0

Check if value is a typed array.

Type Definition
function isTypedArr(val: any): boolean;
NameDesc
valValue to check
returnTrue if value is a typed array
isTypedArr([]); // -> false
isTypedArr(new Uint8Array(8)); // -> true

isUndef

source test1.0.0

Check if value is undefined.

Type Definition
function isUndef(val: any): val is undefined;
NameDesc
valValue to check
returnTrue if value is undefined
isUndef(void 0); // -> true
isUndef(null); // -> false

isUrl

source test1.0.0

Loosely validate an url.

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

isWeakMap

source test1.0.0

Check if value is a WeakMap object.

Type Definition
function isWeakMap(val: any): boolean;
NameDesc
valValue to check
returnTrue if value is a WeakMap
isWeakMap(new Map()); // -> false
isWeakMap(new WeakMap()); // -> true

isWeakSet

source test1.0.0

Check if value is a WeakSet object.

Type Definition
function isWeakSet(val: any): boolean;
NameDesc
valValue to check
returnTrue if value is a WeakSet
isWeakSet(new Set()); // -> false
isWeakSet(new WeakSet()); // -> true

isWindows

source test1.0.0

Check if platform is windows.

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

jsonClone

source test1.12.0

Use JSON parse and stringify to clone object.

Type Definition
function jsonClone<T>(val: T): T;
NameDesc
valValue to clone
returnCloned value
jsonClone({ name: 'licia' }); // -> { name: 'licia' }

jsonp

source test1.0.0

A simple jsonp implementation.

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

Available options:

NameDesc
urlRequest url
dataRequest data
successSuccess callback
param=callbackCallback param
nameCallback name
errorError callback
completeCallback after request
timeoutRequest timeout
jsonp({
    url: 'http://example.com',
    data: { test: 'true' },
    success: function(data) {
        // ...
    }
});

kebabCase

source test1.0.0

Convert string to "kebabCase".

Type Definition
function kebabCase(str: string): string;
NameDesc
strString to convert
returnKebab cased string
kebabCase('fooBar'); // -> foo-bar
kebabCase('foo bar'); // -> foo-bar
kebabCase('foo_bar'); // -> foo-bar
kebabCase('foo.bar'); // -> foo-bar

keyCode

source test1.0.0

Key codes and key names conversion.

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

Get key code's name.

NameDesc
codeKey code
returnCorresponding key name

Get key name's code.

NameDesc
nameKey name
returnCorresponding key code
keyCode(13); // -> 'enter'
keyCode('enter'); // -> 13

keys

source test1.0.0

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

Type Definition
function keys(obj: any): string[];
NameDesc
objObject to query
returnArray of property names
keys({ a: 1 }); // -> ['a']

kill

source test1.4.4

Kill process.

Type Definition
function kill(pid: number): void;
NameDesc
pidProcess ID
kill(9420);

last

source test1.0.0

Get the last element of array.

Type Definition
function last(arr: any[]): any;
NameDesc
arrThe array to query
returnThe last element of array
last([1, 2]); // -> 2

lazyImport

source test1.31.0

Import modules lazily, Proxy is used.

Type Definition
function lazyImport<T>(
    importFn: (moduleId: string) => T,
    dirname?: string
): (moduleId: string) => T;
NameDesc
importFnActual function to require module
dirnameCurrent file folder
returnNew function to require module
const r = lazyImport(require);

const _ = r('underscore');

_.isNumber(5);

lazyRequire

source test1.0.0

Require modules lazily.

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

const _ = r('underscore');

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

levenshtein

source test1.4.8

Levenshtein distance implementation.

Type Definition
function levenshtein(a: string, b: string): number;
NameDesc
aFirst string
bSecond string
returnLevenshtein distance between a and b
levenshtein('cat', 'cake'); // -> 2

linkify

source test1.0.0

Hyperlink urls in a string.

Type Definition
function linkify(str: string, hyperlink?: types.AnyFn): string;
NameDesc
strString to hyperlink
hyperlinkFunction to hyperlink url
returnResult string
const str = 'Official site: http://eustia.liriliri.io';
linkify(str); // -> 'Official site: <a href="http://eustia.liriliri.io">http://eustia.liriliri.io</a>'
linkify(str, function(url) {
    return '<a href="' + url + '" target="_blank">' + url + '</a>';
});

loadCss

source test1.0.0

Inject link tag into page with given href value.

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

loadImg

source test1.0.0

Load image with given src.

Type Definition
function loadImg(src: string, cb?: types.AnyFn): void;
NameDesc
srcImage source
cbOnload callback
loadImg('http://eustia.liriliri.io/img.jpg', function(err, img) {
    console.log(img.width, img.height);
});

loadJs

source test1.0.0

Inject script tag into page with given src value.

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

longest

source test1.0.0

Get the longest item in an array.

Type Definition
function longest(arr: string[]): string;
NameDesc
arrArray to inspect
returnLongest item
longest(['a', 'abcde', 'abc']); // -> 'abcde'

lowerCase

source test1.0.0

Convert string to lower case.

Type Definition
function lowerCase(str: string): string;
NameDesc
strString to convert
returnLower cased string
lowerCase('TEST'); // -> 'test'

lpad

source test1.0.0

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

Type Definition
function lpad(str: string, len: number, chars?: string): string;
NameDesc
strString to pad
lenPadding length
charsString used as padding
returnResult string
lpad('a', 5); // -> '    a'
lpad('a', 5, '-'); // -> '----a'
lpad('abc', 3, '-'); // -> 'abc'
lpad('abc', 5, 'ab'); // -> 'ababc'

ltrim

source test1.0.0

Remove chars or white-spaces from beginning of string.

Type Definition
function ltrim(str: string, chars?: string | string[]): string;
NameDesc
strString to trim
charsCharacters to trim
returnTrimmed string
ltrim(' abc  '); // -> 'abc  '
ltrim('_abc_', '_'); // -> 'abc_'
ltrim('_abc_', ['a', '_']); // -> 'bc_'

map

source test1.0.0

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

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

mapObj

source test1.0.0

Map for objects.

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

matcher

source test1.0.0

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

Type Definition
function matcher(attrs: any): types.AnyFn;
NameDesc
attrsObject of property values to match
returnNew predicate function
const filter = require('licia/filter');

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

max

source test1.0.0

Get maximum value of given numbers.

Type Definition
function max(...num: number[]): number;
NameDesc
...numNumbers to calculate
returnMaximum value
max(2.3, 1, 4.5, 2); // 4.5

md5

source test benchmark1.1.0

MD5 implementation.

Type Definition
function md5(msg: string | number[]): string;
NameDesc
msgMessage to encrypt
returnMD5 hash
md5('licia'); // -> 'e59f337d85e9a467f1783fab282a41d0'

memStorage

source test1.0.0

Memory-backed implementation of the Web Storage API.

Type Definition
const memStorage: typeof window.localStorage;

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

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

memoize

source test1.0.0

Memoize a given function by caching the computed result.

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

mergeArr

source test1.24.0

Merge the contents of arrays together into the first array.

Type Definition
function mergeArr<T, U>(
    first: ArrayLike<T>,
    ...arrays: ArrayLike<U>[]
): ArrayLike<T | U>;
NameDesc
firstArray to merge
arraysArrays to merge into the first array
returnFirst array
const a = [1, 2];
mergeArr(a, [3, 4], [5, 6]);
console.log(a); // -> [1, 2, 3, 4, 5, 6]

mergeSort

source test1.0.0

Merge sort implementation.

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

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

NameDesc
arrArray to sort
cmpComparator
returnSorted array
mergeSort([2, 1]); // -> [1, 2]

meta

source test1.0.0

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

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

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

NameDesc
nameMeta name
returnMeta content

Set meta content.

NameDesc
nameMeta name
contentMeta content
NameDesc
metasObject of name content pairs

remove

Remove metas.

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

methods

source test1.0.0

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

Type Definition
function methods(obj: any): string[];
NameDesc
objObject to check
returnFunction names in object
methods(console); // -> ['Console', 'assert', 'dir', ...]

mime

source test1.5.0

Common mime types.

Type Definition
function mime(name: string): string | undefined;
NameDesc
nameExtension
returnMime type
NameDesc
nameMime type
returnExtension

It contains only the most common file types.

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

min

source test1.0.0

Get minimum value of given numbers.

Type Definition
function min(...num: number[]): number;
NameDesc
...numNumbers to calculate
returnMinimum value
min(2.3, 1, 4.5, 2); // 1

mkdir

source test1.0.0

Recursively create directories.

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

sync

Synchronous version.

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

moment

source test1.0.0

Tiny moment.js like implementation.

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

It only supports a subset of moment.js api.

Available methods

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

Not supported

locale and units like quarter and week.

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

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

morphDom

source test1.25.0

Morph a dom tree to match a target dom tree.

Type Definition
function morphDom(from: Node, to: Node | string): Node;
NameType
fromNode to morph
toNode to be morphed
returnMorphed node
const el1 = document.createElement('div');
el1.className = 'test';
const el2 = document.createElement('div');
el2.className = 'licia';
morphDom(el1, el2);
console.log(el1.className); // -> 'licia'

morse

source test1.19.0

Morse code encoding and decoding.

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

encode

Turn text into Morse code.

NameDesc
txtText to encode
returnMorse code

decode

Decode Morse code into text.

NameDesc
morseMorse code
returnDecoded string
const str = morse.encode('Hello, world.');
// -> '.... . .-.. .-.. --- --..-- ....... .-- --- .-. .-.. -.. .-.-.-'
morse.decode(str); // -> 'Hello, world.'

ms

source test1.0.0

Convert time string formats to milliseconds.

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

Turn time string into milliseconds.

NameDesc
strString format
returnMilliseconds

Turn milliseconds into time string.

NameDesc
numMilliseconds
returnString format
ms('1s'); // -> 1000
ms('1m'); // -> 60000
ms('1.5h'); // -> 5400000
ms('1d'); // -> 86400000
ms('1y'); // -> 31557600000
ms('1000'); // -> 1000
ms(1500); // -> '1.5s'
ms(60000); // -> '1m'

naturalSort

source test1.30.0

Sort values in natural order.

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

negate

source test1.0.0

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

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

nextTick

source test1.0.0

Next tick for both node and browser.

Type Definition
function nextTick(cb: types.AnyFn): void;
NameDesc
cbFunction to call

Use process.nextTick if available.

Otherwise setImmediate or setTimeout is used as fallback.

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

noop

source test1.0.0

A no-operation function.

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

normalizeHeader

source test1.2.0

Normalize http header name.

Type Definition
function normalizeHeader(header: string): string;
NameDesc
headerHeader to normalize
returnNormalized header
normalizeHeader('content-type'); // -> 'Content-Type'
normalizeHeader('etag'); // -> 'ETag'

normalizePath

source test1.0.0

Normalize file path slashes.

Type Definition
function normalizePath(path: string): string;
NameDesc
pathPath to normalize
returnNormalized path
normalizePath('\\foo\\bar\\'); // -> '/foo/bar/'
normalizePath('./foo//bar'); // -> './foo/bar'

normalizePhone

source test1.13.0

Normalize phone numbers into E.164 format.

Type Definition
function normalizePhone(
    phone: string,
    options: {
        countryCode: number;
        trunkPrefix?: boolean;
    }
): string;
NameDesc
phonePhone to normalize
optionsNormalize options
returnNormalized phone

Available options:

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

notify

source test demo1.14.0

Wrapper for the Web Notifications API.

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

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

Notification

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

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

now

source test1.0.0

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

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

objToStr

source test1.0.0

Alias of Object.prototype.toString.

Type Definition
function objToStr(val: any): string;
NameDesc
valSource value
returnString representation of given value
objToStr(5); // -> '[object Number]'

omit

source test1.0.0

Opposite of pick.

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

once

source test1.0.0

Create a function that invokes once.

Type Definition
function once(fn: types.AnyFn): types.AnyFn;
NameDesc
fnFunction to restrict
returnNew restricted function
function init() {}
const initOnce = once(init);
initOnce();
initOnce(); // -> init is invoked once

open

source test1.2.0

Open stuff like url, files.

Type Definition
function open(target: string): any;
NameDesc
targetStuff to open
returnChild process
open('https://eustia.liriliri.io/');

openFile

source test demo1.3.0

Open file dialog to select file in browser.

Type Definition
function openFile(options?: {
    accept?: string;
    multiple?: boolean;
}): Promise<File[]>;
NameDesc
optionsDialog options
returnFiles promise

Available options:

NameDesc
acceptFile types
multiple=falseSelect multiple files or not
openFile({ multiple: true }).then(fileList => {
    console.log(fileList);
});

optimizeCb

source test1.0.0

Used for function context binding.

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

ordinal

source test1.5.2

Add ordinal indicator to number.

Type Definition
function ordinal(num: number): string;
NameDesc
numNumber to add indicator
returnResult ordinal number
ordinal(1); // -> '1st'
ordinal(2); // -> '2nd'

orientation

source test demo1.0.0

Screen orientation helper.

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

on

Bind change event.

off

Unbind change event.

get

Get current orientation(landscape or portrait).

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

pad

source test1.0.0

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

Type Definition
function pad(str: string, len: number, chars?: string): string;
NameDesc
strString to pad
lenPadding length
charsString used as padding
returnResult string
pad('a', 5); // -> '  a  '
pad('a', 5, '-'); // -> '--a--'
pad('abc', 3, '-'); // -> 'abc'
pad('abc', 5, 'ab'); // -> 'babca'
pad('ab', 5, 'ab'); // -> 'ababa'

pairs

source test1.0.0

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

Type Definition
function pairs(obj: any): Array<any[]>;
NameDesc
objObject to convert
returnList of [key, value] pairs
pairs({ a: 1, b: 2 }); // -> [['a', 1], ['b', 2]]

parallel

source test1.0.0

Run an array of functions in parallel.

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

parseArgs

source test1.0.0

Parse command line argument options, the same as minimist.

Type Definition
function parseArgs(
    args: string[],
    options: {
        names: any;
        shorthands: any;
    }
): any;
NameDesc
argsArgument array
optionsParse options
returnParsed result

options

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

parseHtml

source test1.6.0

Simple html parser.

Type Definition
function parseHtml(
    html: string,
    handlers: {
        start?: (tag: string, attrs: any, unary: boolean) => void;
        end?: (tag: string) => void;
        comment?: (text: string) => void;
        text?: (text: string) => void;
    }
): void;
NameDesc
htmlHtml to parse
handlerHandlers
parseHtml('<div>licia</div>', {
    start: (tag, attrs, unary) => {},
    end: tag => {},
    comment: text => {},
    text: text => {}
});

partial

source test1.0.0

Partially apply a function by filling in given arguments.

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

pascalCase

source test1.0.0

Convert string to "pascalCase".

Type Definition
function pascalCase(str: string): string;
NameDesc
strString to convert
returnPascal cased string
pascalCase('fooBar'); // -> FooBar
pascalCase('foo bar'); // -> FooBar
pascalCase('foo_bar'); // -> FooBar
pascalCase('foo.bar'); // -> FooBar

perfNow

source test1.0.0

High resolution time up to microsecond precision.

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

// Do something.

console.log(perfNow() - start);

pick

source test1.0.0

Return a filtered copy of an object.

Type Definition
function pick(
    object: any,
    filter: string | string[] | Function
): any;
NameDesc
objectSource object
filterObject filter
returnFiltered object
pick({ a: 1, b: 2 }, 'a'); // -> {a: 1}
pick({ a: 1, b: 2, c: 3 }, ['b', 'c']); // -> {b: 2, c: 3}
pick({ a: 1, b: 2, c: 3, d: 4 }, function(val, key) {
    return val % 2;
}); // -> {a: 1, c: 3}

pipe

source test1.23.0

Pipe all streams together.

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

pluck

source test1.0.0

Extract a list of property values.

Type Definition
function pluck(object: any, key: string | string[]): any[];
NameDesc
objCollection to iterate over
keyProperty path
returnNew array of specified property
const stooges = [
    { name: 'moe', age: 40 },
    { name: 'larry', age: 50 },
    { name: 'curly', age: 60 }
];
pluck(stooges, 'name'); // -> ['moe', 'larry', 'curly']

precision

source test1.0.0

Find decimal precision of a given number.

Type Definition
function precision(num: number): number;
NameDesc
numNumber to check
returnPrecision
precision(1.234); // -> 3;

prefetch

source test demo1.4.0

Fetch a given url.

Type Definition
function prefetch(url: string): Promise<void>;
NameDesc
urlUrl to prefetch

It uses <link rel=prefetch> if possible.

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

prefix

source test1.0.0

Add vendor prefixes to a CSS attribute.

Type Definition
namespace prefix {
    function dash(name: string): string;
}
function prefix(name: string): string;
NameDesc
nameProperty name
returnPrefixed property name

dash

Create a dasherize version.

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

promisify

source test1.0.0

Convert callback based functions into Promises.

Type Definition
function promisify(
    fn: types.AnyFn,
    multiArgs?: boolean
): types.AnyFn;
NameDesc
fnCallback based function
multiArgs=falseIf callback has multiple success value
returnResult function

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

const fs = require('fs');

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

property

source test1.0.0

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

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

query

source test1.0.0

Parse and stringify url query strings.

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

parse

Parse a query string into an object.

NameDesc
strQuery string
returnQuery object

stringify

Stringify an object into a query string.

NameDesc
objQuery object
returnQuery string
query.parse('foo=bar&eruda=true'); // -> {foo: 'bar', eruda: 'true'}
query.stringify({ foo: 'bar', eruda: 'true' }); // -> 'foo=bar&eruda=true'
query.parse('name=eruda&name=eustia'); // -> {name: ['eruda', 'eustia']}

quickSort

source test benchmark1.0.0

Quick sort implementation.

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

raf

source test1.0.0

Shortcut for requestAnimationFrame.

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

Use setTimeout if native requestAnimationFrame is not supported.

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

random

source test1.0.0

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

Type Definition
function random(
    min: number,
    max?: number,
    floating?: boolean
): number;
NameDesc
minMinimum possible value
maxMaximum possible value
floating=falseFloat or not
returnRandom number
random(1, 5); // -> an integer between 0 and 5
random(5); // -> an integer between 0 and 5
random(1.2, 5.2, true); /// -> a floating-point number between 1.2 and 5.2

randomBytes

source test1.0.0

Random bytes generator.

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

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

NameDesc
sizeNumber of bytes to generate
returnRandom bytes of given length
randomBytes(5); // -> [55, 49, 153, 30, 122]

randomColor

source test demo1.12.0

Random color generator.

Type Definition
function randomColor(): string;
function randomColor(options: {
    count?: number;
    hue?: number;
    lightness?: number;
    format?: string;
    seed?: number;
}): string | string[];
NameDesc
optionsRandom options
returnRandom color

Available options:

NameDesc
count=1Color number
hueHue, number between 0 and 360
lightnessLightness, number between 0 and 1
format=hexColor format, hex, hsl or rgb
seedRandom color seed
randomColor({
    count: 2
}); // -> ['#fed7f4', '#526498']

randomId

source test1.4.8

A tiny id generator, similar to nanoid.

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

randomItem

source test1.0.0

Get a random item from an array.

Type Definition
function randomItem(arr: any[]): any;
NameDesc
arrArray to get
returnRandomly picked item
randomItem([1, 2, 3]); // -> 2

range

source test1.0.0

Create flexibly-numbered lists of integers.

Type Definition
function range(
    start: number,
    end?: number,
    step?: number
): number[];
NameDesc
startStart of the range
endEnd of the range
step=1Value to increment or decrement by
returnList of integers
range(5); // -> [0, 1, 2, 3, 4]
range(0, 5, 2); // -> [0, 2, 4]

rc4

source test1.1.0

RC4 symmetric encryption implementation.

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

encrypt

RC4 encryption, result as base64 string.

decrypt

RC4 decryption, pass base64 string as input.

NameDesc
keySecret key
strString to be encrypted/decrypted
returnEncrypted/decrypted string
rc4.encrypt('licia', 'Hello world'); // -> 'j9y2VpSfR3AdNN8='
rc4.decrypt('licia', 'j9y2VpSfR3AdNN8='); // -> 'Hello world'

ready

source test1.0.0

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

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

reduce

source test benchmark1.0.0

Turn a list of values into a single value.

Type Definition
function reduce<T, TResult>(
    list: types.List<T>,
    iterator: types.MemoIterator<T, TResult>,
    memo?: TResult,
    context?: any
): TResult;
function reduce<T, TResult>(
    list: types.Dictionary<T>,
    iterator: types.MemoObjectIterator<T, TResult>,
    memo?: TResult,
    context?: any
): TResult;
NameDesc
objCollection to iterate over
iterator=identityFunction invoked per iteration
initialInitial value
ctxFunction context
returnAccumulated value
reduce(
    [1, 2, 3],
    function(sum, n) {
        return sum + n;
    },
    0
); // -> 6

reduceRight

source test1.0.0

Right-associative version of reduce.

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

reject

source test1.0.0

Opposite of filter.

Type Definition
function reject<T>(
    list: types.List<T>,
    iterator: types.ListIterator<T, boolean>,
    context?: any
): T[];
function reject<T>(
    object: types.Dictionary<T>,
    iterator: types.ObjectIterator<T, boolean>,
    context?: any
): T[];
NameDesc
objCollection to iterate over
predicateFunction invoked per iteration
ctxPredicate context
returnArray of all values that didn't pass predicate
reject([1, 2, 3, 4, 5], function(val) {
    return val % 2 === 0;
}); // -> [1, 3, 5]

remove

source test1.0.0

Remove all elements from array that predicate returns truthy for and return an array of the removed elements.

Type Definition
function remove<T, TResult>(
    list: types.List<T>,
    iterator: types.ListIterator<T, boolean>,
    context?: any
): TResult[];

Unlike filter, this method mutates array.

NameDesc
listCollection to iterate over
iteratorFunction invoked per iteration
contextPredicate context
returnArray of all values that are removed
const arr = [1, 2, 3, 4, 5];
const evens = remove(arr, function(val) {
    return val % 2 === 0;
});
console.log(arr); // -> [1, 3, 5]
console.log(evens); // -> [2, 4]

repeat

source test1.0.0

Repeat string n-times.

Type Definition
function repeat(str: string, n: number): string;
NameDesc
strString to repeat
nRepeat times
returnRepeated string
repeat('a', 3); // -> 'aaa'
repeat('ab', 2); // -> 'abab'
repeat('*', 0); // -> ''

replaceAll

source test1.23.0

Replace all instance in a string.

Type Definition
function replaceAll(
    str: string,
    substr: string,
    newSubstr: string
): string;
NameDesc
strSource string
substrString to be replaced
newSubstrString to replace substr
returnNew string with all substr replaced
replaceAll('hello world goodbye world', 'world', 'licia'); // -> 'hello licia goodbye licia'

restArgs

source test1.0.0

This accumulates the arguments passed into an array, after a given index.

Type Definition
function restArgs(
    fn: types.AnyFn,
    startIndex?: number
): types.AnyFn;
NameDesc
functionFunction that needs rest parameters
startIndexThe start index to accumulates
returnGenerated function with rest parameters
const paramArr = restArgs(function(rest) {
    return rest;
});
paramArr(1, 2, 3, 4); // -> [1, 2, 3, 4]

reverse

source test benchmark1.16.0

Reverse array without mutating it.

Type Definition
function reverse(arr: any[]): any[];
NameDesc
arrArray to modify
returnReversed array
reverse([1, 2, 3]); // -> [3, 2, 1]

rgbToHsl

source test1.0.0

Convert rgb to hsl.

Type Definition
function rgbToHsl(rgb: number[]): number[];
NameDesc
rgbRgb values
returnHsl values
rgbToHsl([52, 203, 165, 0.8]); // -> [165, 59, 50, 0.8]

ric

source test1.4.0

Shortcut for requestIdleCallback.

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

Use setTimeout if requestIdleCallback is not supported.

const id = ric(function() {
    // Called during a browser's idle periods
});
ric.cancel(id);

rmCookie

source test1.0.0

Loop through all possible path and domain to remove cookie.

Type Definition
function rmCookie(key: string): void;
NameDesc
keyCookie key
rmCookie('test');

rmdir

source test1.0.0

Recursively remove directories.

Type Definition
function rmdir(dir: string, cb?: types.AnyFn): void;
NameDesc
dirDirectory to remove
cbCallback
rmdir('/tmp/foo/bar/baz', function(err) {
    if (err) console.log(err);
    else console.log('Done');
});

root

source test1.0.0

Root object reference, global in nodeJs, window in browser.

Type Definition
const root: any;

rpad

source test1.0.0

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

Type Definition
function rpad(str: string, len: number, chars?: string): string;
NameDesc
strString to pad
lenPadding length
charsString used as padding
returnResult string
rpad('a', 5); // -> 'a    '
rpad('a', 5, '-'); // -> 'a----'
rpad('abc', 3, '-'); // -> 'abc'
rpad('abc', 5, 'ab'); // -> 'abcab'

rtrim

source test1.0.0

Remove chars or white-spaces from end of string.

Type Definition
function rtrim(str: string, chars?: string | string[]): string;
NameDesc
strString to trim
charsCharacters to trim
returnTrimmed string
rtrim(' abc  '); // -> ' abc'
rtrim('_abc_', '_'); // -> '_abc'
rtrim('_abc_', ['c', '_']); // -> '_ab'

safeCb

source test1.0.0

Create callback based on input value.

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

safeDel

source test1.0.0

Delete object property.

Type Definition
function safeDel(obj: any, path: string | string[]): any;
NameDesc
objObject to query
pathPath of property to delete
returnDeleted value or undefined
const obj = { a: { aa: { aaa: 1 } } };
safeDel(obj, 'a.aa.aaa'); // -> 1
safeDel(obj, ['a', 'aa']); // -> {}
safeDel(obj, 'a.b'); // -> undefined

safeGet

source test1.0.0

Get object property, don't throw undefined error.

Type Definition
function safeGet(obj: any, path: string | string[]): any;
NameDesc
objObject to query
pathPath of property to get
returnTarget value or undefined
const obj = { a: { aa: { aaa: 1 } } };
safeGet(obj, 'a.aa.aaa'); // -> 1
safeGet(obj, ['a', 'aa']); // -> {aaa: 1}
safeGet(obj, 'a.b'); // -> undefined

safeSet

source test1.0.0

Set value at path of object.

Type Definition
function safeSet(
    obj: any,
    path: string | string[],
    val: any
): void;

If a portion of path doesn't exist, it's created.

NameDesc
objObject to modify
pathPath of property to set
valValue to set
const obj = {};
safeSet(obj, 'a.aa.aaa', 1); // obj = {a: {aa: {aaa: 1}}}
safeSet(obj, ['a', 'aa'], 2); // obj = {a: {aa: 2}}
safeSet(obj, 'a.b', 3); // obj = {a: {aa: 2, b: 3}}

safeStorage

source test1.0.0

Use storage safely in safari private browsing and older browsers.

Type Definition
function safeStorage(type?: string): typeof window.localStorage;
NameDesc
type='local'local or session
returnSpecified storage
const localStorage = safeStorage('local');
localStorage.setItem('licia', 'util');

sameOrigin

source test1.26.0

Check if two urls pass the same origin policy.

Type Definition
function sameOrigin(url1: string, url2: string): boolean;
NameDesc
url1Url to check
url2Url to check
returnTrue if urls pass same origin policy
const url1 = 'http://example.com/a.html';
const url2 = 'http://example.com/b.html';
const url3 = 'http://licia.liriliri.io';
sameOrigin(url1, url2); // -> true
sameOrigin(url1, url3); // -> false

sample

source test1.0.0

Sample random values from a collection.

Type Definition
function sample(obj: any, n: number): any[];
NameDesc
objCollection to sample
nNumber of values
returnArray of sample values
sample([2, 3, 1], 2); // -> [2, 3]
sample({ a: 1, b: 2, c: 3 }, 1); // -> [2]

scrollTo

source test demo1.0.0

Scroll to a target with animation.

Type Definition
function scrollTo(
    target: Element | string | number,
    options: {
        tolerance?: number;
        duration?: number;
        easing?: string | Function;
        callback?: types.AnyFn;
    }
);
NameDesc
targetScroll target
optionsScroll options

Options

NameDesc
tolerance=0Tolerance of target to scroll
duration=800Scroll duration
easing=outQuartEasing function
callback=noopFunction to run once scrolling complete
scrollTo('body', {
    tolerance: 0,
    duration: 800,
    easing: 'outQuart',
    callback: function() {}
});

seedRandom

source test1.12.0

Seeded random number generator.

Type Definition
function seedRandom(
    seed: number,
    min?: number,
    max?: number,
    floating?: boolean
): () => number;
NameDesc
seedRandom seed
min=0Min possible value
max=1Maximum possible value
floating=trueFloat or not
returnFunction that generates random number sequence
const random = seedRandom(19920719, 0, 100, false);
random(); // -> 7
random(); // -> 68

selectionSort

source test1.0.0

Selection sort implementation.

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

selector

source test1.14.0

Css selector parser and serializer.

Type Definition
namespace selector {
    interface IToken {
        type: string;
        value: string;
    }
}
const selector: {
    parse(selector: string): Array<selector.IToken[]>;
    stringify(selector: Array<selector.IToken[]>): string;
};

parse

Parse css selector into js object.

NameDesc
selectorCss selector
returnParsed js object

stringify

Stringify object into an css selector.

NameDesc
groupsObject to stringify
returnCss selector
const groups = selector.parse('#test, input.user[name="licia"]');
// -> [[{type: 'id', value: 'test'}],[{type: 'tag', value: 'input'}...]]
selector.stringify(groups);

shebang

source test1.23.0

Get command from a shebang.

Type Definition
function shebang(str: string): string | void;
NameDesc
strString to get command
returnShebang command
shebang('#!/usr/bin/env node'); // -> '/usr/bin/env node'
shebang('#!/bin/bash'); // -> '/bin/bash'
shebang('node'); // -> undefined

shellSort

source test1.5.0

Shell sort implementation.

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

shuffle

source test1.0.0

Randomize the order of the elements in a given array.

Type Definition
function shuffle(arr: any[]): any[];
NameDesc
arrArray to randomize
returnRandomized Array
shuffle([1, 2, 3]); // -> [3, 1, 2]

size

source test1.0.0

Get size of object or length of array like object.

Type Definition
function size(obj: any): number;
NameDesc
objCollection to inspect
returnCollection size
size({ a: 1, b: 2 }); // -> 2
size([1, 2, 3]); // -> 3

sizeof

source test1.14.0

Get approximate size of a js object.

Type Definition
function sizeof(obj: any): number;
NameDesc
objObject to calculate
returnSize in bytes

A char of string is counted as 2 bytes. And 4 bytes for boolean, 8 bytes for number.

Object keys are treated as strings.

sizeof('a'); // -> 2
sizeof(8); // -> 8
sizeof(false); // -> 4
sizeof(function() {}); // -> 0
sizeof({ a: 'b' }); // -> 4

sleep

source test1.4.1

Resolve a promise after a specified timeout.

Type Definition
function sleep(timeout: number): Promise<void>;
NameDesc
timeoutSleep timeout
(async function() {
    await sleep(2000);
})();

slice

source test1.0.0

Create slice of source array or array-like object.

Type Definition
function slice(
    array: any[],
    start?: number,
    end?: number
): any[];
NameDesc
arrayArray to slice
start=0Start position
end=array.lengthEnd position, not included
slice([1, 2, 3, 4], 1, 2); // -> [2]

slugify

source test1.7.0

Slugify a string.

Type Definition
function slugify(
    str: string,
    replacement?: { [index: string]: string }
): string;
NameDesc
strString to slugify
replacementCustom replacement
returnSlugified string
slugify('I ♥ pony'); // -> 'I-love-pony'
slugify('I ♥ pony', { ' ': '_' }); // -> 'I_love_pony'

snakeCase

source test1.0.0

Convert string to "snakeCase".

Type Definition
function snakeCase(str: string): string;
NameDesc
strString to convert
returnSnake cased string
snakeCase('fooBar'); // -> foo_bar
snakeCase('foo bar'); // -> foo_bar
snakeCase('foo.bar'); // -> foo_bar

some

source test1.0.0

Check if predicate return truthy for any element.

Type Definition
function some<T>(
    list: types.List<T>,
    iterator?: types.ListIterator<T, boolean>,
    context?: any
): boolean;
function some<T>(
    object: types.Dictionary<T>,
    iterator?: types.ObjectIterator<T, boolean>,
    context?: any
): boolean;
NameDesc
objCollection to iterate over
predicateFunction to invoked per iteration
ctxPredicate context
returnTrue if any element passes the predicate check
some([2, 5], function(val) {
    return val % 2 === 0;
}); // -> true

sortBy

source test1.0.0

Return an array of elements sorted in ascending order by results of running each element through iteratee.

Type Definition
function sortBy(
    arr: any,
    iterator?: types.AnyFn,
    ctx?: any
): any[];
NameDesc
arrCollection to iterate over
iterator=identityIterator to sort by
ctxIterator context
returnNew sorted array
sortBy([1, 2, 3, 4, 5, 6], function(num) {
    return Math.sin(num);
}); // -> [5, 4, 6, 3, 1, 2]

sortKeys

source test1.17.0

Sort keys of an object.

Type Definition
function sortKeys(
    obj: object,
    options?: {
        deep?: boolean;
        comparator?: types.AnyFn;
    }
): object;
NameDesc
objObject to sort
optionsSort options
returnObject with sorted keys

Available options:

NameDesc
deep=falseSort keys recursively
comparatorComparator
sortKeys(
    { b: { d: 2, c: 1 }, a: 0 },
    {
        deep: true
    }
); // -> {a: 0, b: {c: 1, d: 2}}

spaceCase

source test1.0.0

Convert string to "spaceCase".

Type Definition
function spaceCase(str: string): string;
NameDesc
strString to convert
returnSpace cased string
spaceCase('fooBar'); // -> foo bar
spaceCase('foo.bar'); // -> foo bar
spaceCase('foo.bar'); // -> foo bar

splitCase

source test1.0.0

Split different string case to an array.

Type Definition
function splitCase(str: string): string[];
NameDesc
strString to split
returnResult array
splitCase('foo-bar'); // -> ['foo', 'bar']
splitCase('foo bar'); // -> ['foo', 'bar']
splitCase('foo_bar'); // -> ['foo', 'bar']
splitCase('foo.bar'); // -> ['foo', 'bar']
splitCase('fooBar'); // -> ['foo', 'bar']
splitCase('foo-Bar'); // -> ['foo', 'bar']

splitPath

source test1.0.0

Split path into dir, name and ext.

Type Definition
function splitPath(
    path: string
): {
    dir: string;
    name: string;
    ext: string;
};
NameDesc
pathPath to split
returnObject containing dir, name and ext
splitPath('f:/foo/bar.txt'); // -> {dir: 'f:/foo/', name: 'bar.txt', ext: '.txt'}
splitPath('/home/foo/bar.txt'); // -> {dir: '/home/foo/', name: 'bar.txt', ext: '.txt'}

stackTrace

source test1.5.3

Get CallSite objects in v8.

Type Definition
function stackTrace(): any[];

Stack trace API

stackTrace(); // -> List of CallSite objects

startWith

source test1.0.0

Check if string starts with the given target string.

Type Definition
function startWith(str: string, prefix: string): boolean;
NameDesc
strString to search
prefixString prefix
returnTrue if string starts with prefix
startWith('ab', 'a'); // -> true

strHash

source test1.0.0

String hash function using djb2.

Type Definition
function strHash(str: string): number;
NameDesc
strString to hash
returnHash result
strHash('test'); // -> 2090770981

strToBytes

source test1.1.0

Convert string into bytes.

Type Definition
function strToBytes(str: string, encoding?: string): number[];
NameDesc
strString to convert
encoding=utf8Encoding of string
returnBytes array

Supported encoding: utf8, hex, base64

strToBytes('licia'); // -> [108, 105, 99, 105, 97]
strToBytes('qK6b/w==', 'base64'); // -> [168, 174, 155, 255]

strTpl

source test1.23.0

Simple string template.

Type Definition
function strTpl(str: string, data: types.PlainObj<any>): string;
NameDesc
strTemplate string
dataData to pass in
returnResult string
strTpl('Hello, {{name.first}}!', { name: { first: 'licia' } }); // -> 'Hello, licia!'

strWidth

source test1.24.0

Get string's visual width.

Type Definition
function strWidth(str: string): number;
NameDesc
strString to get width
returnVisual width
strWidth('Hello \nworld!'); // -> 12
strWidth('\u001b[4m你好,世界!\u001b[0m'); // -> 12

stringify

source test1.0.0

JSON stringify with support for circular object, function etc.

Type Definition
function stringify(obj: any, spaces?: number): string;

Undefined is treated as null value.

NameDesc
objObject to stringify
spacesIndent spaces
returnStringified object
stringify({ a: function() {} }); // -> '{"a":"[Function function () {}]"}'
const obj = { a: 1, b: {} };
obj.b = obj;
stringify(obj); // -> '{"a":1,"b":"[Circular ~]"}'

stringifyAll

source test demo1.5.5

Stringify object into json with types.

Type Definition
namespace stringifyAll {
    function parse(str: string): any;
}
function stringifyAll(
    obj: any,
    options?: {
        unenumerable?: boolean;
        symbol?: boolean;
        accessGetter?: boolean;
        timeout?: number;
        depth?: number;
        ignore?: any[];
    }
): string;
NameDesc
objObject to stringify
optionsStringify options
returnStringified object

Available options:

NameDesc
unenumerable=falseInclude unenumerable keys
symbol=falseInclude symbol keys
accessGetter=falseAccess getter value
timeout=0Timeout of stringify
depth=0Max depth of recursion
ignoreValues to ignore

When time is out, all remaining values will all be "Timeout".

parse

Parse result string back to object.

NameType
objString to parse
returnResult object
stringifyAll(function test() {}); // -> '{"value":"function test() {}","type":"Function",...}'

stripAnsi

source test1.0.0

Strip ansi codes from a string.

Type Definition
function stripAnsi(str: string): string;
NameDesc
strString to strip
returnResult string
stripAnsi('\u001b[4mcake\u001b[0m'); // -> 'cake'

stripBom

source test1.38.0

Strip UTF-8 byte order mark.

Type Definition
function stripBom(str: string): string;
NameDesc
strString to strip
returnResult string
stripBom('\uFEFFlicia'); // -> 'licia'

stripCmt

source test1.0.0

Strip comments from source code.

Type Definition
function stripCmt(str: string): string;
NameDesc
strSource code
returnCode without comments
stripCmt('// comment \n var a = 5; \/* comment2\n * comment3\n *\/'); // -> ' var a = 5; '

stripColor

source test1.0.0

Strip ansi color codes from a string.

Type Definition
function stripColor(str: string): string;
NameDesc
strString to strip
returnResult string
stripColor('\u001b[31mred\u001b[39m'); // -> 'red'

stripHtmlTag

source test1.0.0

Strip html tags from a string.

Type Definition
function stripHtmlTag(str: string): string;
NameDesc
strString to strip
returnResult string
stripHtmlTag('<p>Hello</p>'); // -> 'Hello'

stripIndent

source test1.5.4

Strip indentation from multi-line strings.

Type Definition
function stripIndent(str: string): string;
function stripIndent(
    literals: TemplateStringsArray,
    ...placeholders: any[]
): string;
NameDesc
strString to strip
returnResult string

It can be used as function or template tag.

stripIndent`
    Test string
        * item one
        * item two
`; // -> 'Test string\n    * item one\n    * item two'

stripNum

source test1.15.0

Strip number to a specified precision.

Type Definition
function stripNum(num: number, precision?: number): number;
NameDesc
numNumber to strip
precision=12Precision
returnResult number
stripNum(0.1 + 0.2); // -> 0.3

sum

source test1.0.0

Compute sum of given numbers.

Type Definition
function sum(...num: number[]): number;
NameDesc
...numNumbers to calculate
returnSum of numbers
sum(1, 2, 5); // -> 8

swap

source test1.0.0

Swap two items in an array.

Type Definition
function swap(arr: any[], a: number, b: number): any[];
NameDesc
arrArray to swap
aFirst index
bSecond index
returnArray given
const arr = [1, 2];
swap(arr, 0, 1); // -> [2, 1]

table

source test1.24.0

Output table string.

Type Definition
function table(rows: Array<string[]>): string;
NameDesc
rowsTable data
returnTable string
table([
    ['', 'firstName', 'lastName'],
    ['daughter', 'Emily', 'Smith'],
    ['father', 'John', 'Smith'],
    ['mother', 'Jane', 'Smith']
]);

template

source test1.0.0

Compile JavaScript template into function that can be evaluated for rendering.

Type Definition
function template(str: string, util?: any): types.AnyFn;
NameDesc
strTemplate string
utilUtility functions
returnCompiled template function
template('Hello <%= name %>!')({ name: 'licia' }); // -> 'Hello licia!'
template('<p><%- name %></p>')({ name: '<licia>' }); // -> '<p>&lt;licia&gt;</p>'
template('<%if (echo) {%>Hello licia!<%}%>')({ echo: true }); // -> 'Hello licia!'
template('<p><%= util["upperCase"](name) %></p>', {
    upperCase: function(str) {
        return str.toLocaleUpperCase();
    }
})({ name: 'licia' }); // -> '<p>LICIA</p>'

throttle

source test1.0.0

Return a new throttled version of the passed function.

Type Definition
function throttle<T extends types.AnyFn>(fn: T, wait: number): T;
NameDesc
fnFunction to throttle
waitNumber of milliseconds to delay
returnNew throttled function
const updatePos = throttle(function() {}, 100);
// $(window).scroll(updatePos);

through

source test1.0.0

Tiny wrapper of stream Transform.

Type Definition
import stream = require('stream');
namespace through {
    interface ThroughConstructor extends stream.Transform {
        new (opts?: stream.DuplexOptions): stream.Transform;
        (opts?: stream.DuplexOptions): stream.Transform;
    }
    type TransformCallback = (err?: any, data?: any) => void;
    type TransformFunction = (
        this: stream.Transform,
        chunk: any,
        enc: string,
        callback: TransformCallback
    ) => void;
    type FlushCallback = (
        this: stream.Transform,
        flushCallback: () => void
    ) => void;
    function obj(
        transform?: TransformFunction,
        flush?: FlushCallback
    ): stream.Transform;
    function ctor(
        transform?: TransformFunction,
        flush?: FlushCallback
    ): ThroughConstructor;
    function ctor(
        opts?: stream.DuplexOptions,
        transform?: TransformFunction,
        flush?: FlushCallback
    ): ThroughConstructor;
}
function through(
    transform?: through.TransformFunction,
    flush?: through.FlushCallback
): stream.Transform;
function through(
    opts?: stream.DuplexOptions,
    transform?: through.TransformFunction,
    flush?: through.FlushCallback
): stream.Transform;
NameDesc
opts={}Options to initialize stream
transformTransform implementation
flushFlush implementation

obj

Shortcut for setting objectMode to true.

ctor

Return a class that extends stream Transform.

const fs = require('fs');
fs.createReadStream('in.txt')
    .pipe(
        through(function(chunk, enc, cb) {
            // Do something to chunk
            this.push(chunk);
            cb();
        })
    )
    .pipe(fs.createWriteStream('out.txt'));

timeAgo

source test1.0.0

Format datetime with *** time ago statement.

Type Definition
function timeAgo(
    date: Date | number,
    now?: Date | number
): string;
NameDesc
dateDate to calculate
now=new DateCurrent date
returnFormatted time ago string
const now = new Date().getTime();
timeAgo(now - 1000 * 6); // -> just now
timeAgo(now - 1000 * 15); // -> 15 seconds ago
timeAgo(now + 1000 * 60 * 15); // -> in 15 minutes
timeAgo(now - 1000 * 60 * 60 * 5, now); // -> 5 hours ago

timeTaken

source test1.0.0

Get execution time of a function.

Type Definition
function timeTaken(fn: types.AnyFn): number;
NameDesc
fnFunction to measure time
returnExecution time, ms
timeTaken(function() {
    // Do something.
}); // -> Time taken to execute given function.

times

source test1.2.0

Invoke given function n times.

Type Definition
function times<T>(
    n: number,
    fn: (n: number) => T,
    ctx?: any
): T[];
NameDesc
nTimes to invoke function
fnFunction invoked per iteration
ctxFunction context
returnArray of results
times(3, String); // -> ['0', '1', '2']

toArr

source test1.0.0

Convert value to an array.

Type Definition
function toArr(val: any): any[];
NameDesc
valValue to convert
returnConverted array
toArr({ a: 1, b: 2 }); // -> [{a: 1, b: 2}]
toArr('abc'); // -> ['abc']
toArr(1); // -> [1]
toArr(null); // -> []

toAsync

source test1.8.0

Use generator like async/await.

Type Definition
function toAsync(fn: types.AnyFn): types.AnyFn;
NameDesc
fnGenerator function
returnResult function
const sleep = require('licia/sleep');

const fn = toAsync(function*() {
    yield sleep(200);
    return 'licia';
});

fn().then(str => {});

toBool

source test1.0.0

Convert value to a boolean.

Type Definition
function toBool(val: any): boolean;
NameDesc
valValue to convert
returnConverted boolean
toBool(true); // -> true
toBool(null); // -> false
toBool(1); // -> true
toBool(0); // -> false
toBool('0'); // -> false
toBool('1'); // -> true
toBool('false'); // -> false

toDate

source test1.0.0

Convert value to a Date.

Type Definition
function toDate(val: any): Date;
NameDesc
valValue to convert
returnConverted Date
toDate('20180501');
toDate('2018-05-01');
toDate(1525107450849);

toEl

source test1.0.0

Convert html string to dom elements.

Type Definition
function toEl(str: string): Element;

There should be only one root element.

NameDesc
strHtml string
returnHtml element
toEl('<div>test</div>');

toInt

source test1.0.0

Convert value to an integer.

Type Definition
function toInt(val: any): number;
NameDesc
valValue to convert
returnConverted integer
toInt(1.1); // -> 1
toInt(undefined); // -> 0

toNum

source test1.0.0

Convert value to a number.

Type Definition
function toNum(val: any): number;
NameDesc
valValue to process
returnResult number
toNum('5'); // -> 5

toSrc

source test1.0.0

Convert function to its source code.

Type Definition
function toSrc(fn: types.AnyFn): string;
NameDesc
fnFunction to convert
returnSource code
toSrc(Math.min); // -> 'function min() { [native code] }'
toSrc(function() {}); // -> 'function () { }'

toStr

source test1.0.0

Convert value to a string.

Type Definition
function toStr(val: any): string;
NameDesc
valValue to convert
returnResult string
toStr(null); // -> ''
toStr(1); // -> '1'
toStr(false); // -> 'false'
toStr([1, 2, 3]); // -> '1,2,3'

topoSort

source test1.0.0

Topological sorting algorithm.

Type Definition
function topoSort(edges: any[]): any[];
NameDesc
edgesDependencies
returnSorted order
topoSort([
    [1, 2],
    [1, 3],
    [3, 2]
]); // -> [1, 3, 2]

trigger

source test1.0.0

Trigger browser events.

Type Definition
function trigger(
    el: Element | Document,
    type: string,
    options?: any
): void;
function trigger(type: string, options?: any): void;
NameDesc
el=documentElement to trigger
typeEvent type
optionsOptions
trigger(document.getElementById('test'), 'mouseup');
trigger('keydown', { keyCode: 65 });

trim

source test benchmark1.0.0

Remove chars or white-spaces from beginning end of string.

Type Definition
function trim(str: string, chars?: string | string[]): string;
NameDesc
strString to trim
charsCharacters to trim
returnTrimmed string
trim(' abc  '); // -> 'abc'
trim('_abc_', '_'); // -> 'abc'
trim('_abc_', ['a', 'c', '_']); // -> 'b'

truncate

source test1.20.0

Truncate a string to a specific width.

Type Definition
function truncate(
    txt: string,
    width: number,
    options?: {
        ellipsis?: string;
        separator: string;
    }
): string;
NameDesc
txtText to truncate
widthMaximum string length
optionsOptions object
returnTruncated string

Options:

NameDesc
ellipsis='...'String to indicate text is omitted
separatorSeparator pattern to truncate to
truncate('ORA ORA ORA ORA ORA ORA', 12); // -> 'ORA ORA O...'
truncate('ORA ORA ORA ORA ORA ORA', 10, {
    separator: ' ',
    ellipsis: '……'
}); // -> 'ORA ORA……'

tryIt

source test1.0.0

Run function in a try catch.

Type Definition
function tryIt(fn: types.AnyFn, cb?: types.AnyFn): void;
NameDesc
fnFunction to try catch
cbCallback
tryIt(
    function() {
        // Do something that might cause an error.
    },
    function(err, result) {
        if (err) console.log(err);
    }
);

type

source test1.0.0

Determine the internal JavaScript [[Class]] of an object.

Type Definition
function type(val: any, lowerCase?: boolean): string;
NameDesc
valValue to get type
lowerCase=trueLowerCase result
returnType of object
type(5); // -> 'number'
type({}); // -> 'object'
type(function() {}); // -> 'function'
type([]); // -> 'array'
type([], false); // -> 'Array'
type(async function() {}, false); // -> 'AsyncFunction'

types

source test1.0.0

Used for typescript definitions only.

Type Definition
namespace types {
    interface Collection<T> {}
    interface List<T> extends Collection<T> {
        [index: number]: T;
        length: number;
    }
    interface ListIterator<T, TResult> {
        (value: T, index: number, list: List<T>): TResult;
    }
    interface Dictionary<T> extends Collection<T> {
        [index: string]: T;
    }
    interface ObjectIterator<T, TResult> {
        (element: T, key: string, list: Dictionary<T>): TResult;
    }
    interface MemoIterator<T, TResult> {
        (prev: TResult, curr: T, index: number, list: List<T>): TResult;
    }
    interface MemoObjectIterator<T, TResult> {
        (prev: TResult, curr: T, key: string, list: Dictionary<T>): TResult;
    }
    type Fn<T> = (...args: any[]) => T;
    type AnyFn = Fn<any>;
    type PlainObj<T> = { [name: string]: T };
}
const types: {};

ucs2

source test1.0.0

UCS-2 encoding and decoding.

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

encode

Create a string using an array of code point values.

NameDesc
arrArray of code points
returnEncoded string

decode

Create an array of code point values using a string.

NameDesc
strInput string
returnArray of code points
ucs2.encode([0x61, 0x62, 0x63]); // -> 'abc'
ucs2.decode('abc'); // -> [0x61, 0x62, 0x63]
'𝌆'.length; // -> 2
ucs2.decode('𝌆').length; // -> 1

uncaught

source test demo1.2.0

Handle global uncaught errors and promise rejections.

Type Definition
const uncaught: {
    start(): void;
    stop(): void;
    addListener(fn: (err: Error) => void): void;
    rmListener(fn: (err: Error) => void): void;
    rmAllListeners(): void;
};

start

Start handling of errors.

stop

Stop handling.

addListener

Add listener for handling errors.

NameDesc
fnError listener

rmListener

Remove listener.

rmAllListeners

Remove all listeners.

uncaught.start();
uncaught.addListener(err => {
    // Do something.
});

unescape

source test1.0.0

Convert HTML entities back, the inverse of escape.

Type Definition
function unescape(str: string): string;
NameDesc
strString to unescape
returnUnescaped string
unescape('You &amp; Me'); // -> 'You & Me'

union

source test1.0.0

Create an array of unique values, in order, from all given arrays.

Type Definition
function union(...arr: Array<any[]>): any[];
NameDesc
...arrArrays to inspect
returnNew array of combined values
union([2, 1], [4, 2], [1, 2]); // -> [2, 1, 4]

uniqId

source test1.0.0

Generate a globally-unique id.

Type Definition
function uniqId(prefix?: string): string;
NameDesc
prefixId prefix
returnGlobally-unique id
uniqId('eustia_'); // -> 'eustia_xxx'

unique

source test1.0.0

Create duplicate-free version of an array.

Type Definition
function unique(
    arr: any[],
    cmp?: (a: any, b: any) => boolean | number
): any[];
NameDesc
arrArray to inspect
cmpFunction for comparing values
returnNew duplicate free array
unique([1, 2, 3, 1]); // -> [1, 2, 3]

universalify

source test1.7.0

Make an async function support both promises and callbacks.

Type Definition
function universalify(
    fn: types.AnyFn,
    type: string
): types.AnyFn;
NameDesc
fnAsync function
typeSource type, promise or callback
returnResult function
function callbackFn(str, cb) {
    setTimeout(() => {
        cb(null, str);
    }, 10);
}

const fn = universalify(callbackFn, 'callback');
fn('licia', (err, result) => {
    console.log(result); // -> 'licia'
});
fn('licia').then(result => {
    console.log(result); // -> 'licia'
});

unzip

source test1.0.0

Opposite of zip.

Type Definition
declare function unzip(arr: Array<any[]>): Array<any[]>;
NameDesc
arrArray of grouped elements to process
returnNew array of regrouped elements
unzip([
    ['a', 1, true],
    ['b', 2, false]
]); // -> [['a', 'b'], [1, 2], [true, false]]

upperCase

source test1.0.0

Convert string to upper case.

Type Definition
function upperCase(str: string): string;
NameDesc
strString to convert
returnUppercased string
upperCase('test'); // -> 'TEST'

upperFirst

source test1.0.0

Convert the first character of string to upper case.

Type Definition
function upperFirst(str: string): string;
NameDesc
strString to convert
returnConverted string
upperFirst('red'); // -> Red

use

source test1.0.0

Use modules that is created by define.

Type Definition
function use(requires: string[], method: types.AnyFn): void;
function use(method: types.AnyFn): void;
NameDesc
requiresDependencies
methodCodes to be executed
// define('A', () => 'A');
use(['A'], function(A) {
    console.log(A + 'B'); // -> 'AB'
});

utf8

source test1.0.0

UTF-8 encoding and decoding.

Type Definition
const utf8: {
    encode(str: string): string;
    decode(str: string, safe?: boolean): string;
};

encode

Turn any UTF-8 decoded string into UTF-8 encoded string.

NameDesc
strString to encode
returnEncoded string

decode

Turn any UTF-8 encoded string into UTF-8 decoded string.

NameDesc
strString to decode
safe=falseSuppress error if true
returnDecoded string
utf8.encode('\uD800\uDC00'); // ->  '\xF0\x90\x80\x80'
utf8.decode('\xF0\x90\x80\x80'); // -> '\uD800\uDC00'

uuid

source test benchmark1.0.0

RFC4122 version 4 compliant uuid generator.

Type Definition
function uuid(): string;

Check RFC4122 4.4 for reference.

uuid(); // -> '53ce0497-6554-49e9-8d79-347406d2a88b'

values

source test1.0.0

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

Type Definition
function values(obj: any): any[];
NameDesc
objObject to query
returnArray of property values
values({ one: 1, two: 2 }); // -> [1, 2]

viewportScale

source test1.0.0

Get viewport scale.

Type Definition
function viewportScale(): number;
viewportScale(); // -> 3

vlq

source test1.4.0

Variable-length quantity encoding and decoding.

Type Definition
const vlq: {
    encode(number: number | number[]): string;
    decode(string: string): number[];
};

encode

Encode numbers into vlq string.

NameDesc
numberNumber to encode
returnEncoded string

decode

Decode vlq string into numbers.

NameDesc
stringString to decode
returnDecoded numbers
vlq.encode(123); // -> '2H'
vlq.encode([123, 456, 789]); // -> '2HwcqxB'
vlq.decode('2H'); // -> [123]
vlq.decode('2HwcqxB'); // -> [123, 456, 789]

waitUntil

source test1.4.3

Wait until function returns a truthy value.

Type Definition
function waitUntil(
    condition: types.AnyFn,
    timeout?: number,
    interval?: number
): Promise<any>;
NameDesc
conditionCondition function
timeout=0Timeout
interval=250Wait interval
let a = 5;
setTimeout(() => (a = 10), 500);
waitUntil(() => a === 10).then(() => {
    console.log(a); // -> 10
});

waterfall

source test1.0.0

Run an array of functions in series.

Type Definition
function waterfall(tasks: types.AnyFn[], cb?: types.AnyFn): void;
NameDesc
tasksArray of functions
cbCallback once completed
waterfall(
    [
        function(cb) {
            cb(null, 'one');
        },
        function(arg1, cb) {
            // arg1 -> 'one'
            cb(null, 'done');
        }
    ],
    function(err, result) {
        // result -> 'done'
    }
);

wordWrap

source test1.27.0

Wrap a string to a given length.

Type Definition
function wordWrap(txt: string, width: number): string;
NameDesc
txtText to wrap
widthText width
returnString wrapped at given length
wordWrap('Licia is a utility library.', 10);
// -> 'Licia is \na utility \nlibrary.'

wordsToBytes

source test1.16.0

Convert 32-bit words to bytes.

Type Definition
function wordsToBytes(words: number[]): number[];
NameDesc
wordsWord array
returnByte array
wordsToBytes([0x12345678]); // -> [0x12, 0x34, 0x56, 0x78]

workerize

source test demo1.0.0

Move a stand-alone function to a worker thread.

Type Definition
function workerize(fn: types.AnyFn): types.AnyFn;
NameDesc
fnFunction to turn
returnWorkerized Function
const worker = workerize(function(a, b) {
    return a + b;
});
worker(1, 2).then(function(value) {
    console.log(value); // -> 3
});

wrap

source test1.0.0

Wrap the function inside a wrapper function, passing it as the first argument.

Type Definition
function wrap(
    fn: types.AnyFn,
    wrapper: types.AnyFn
): types.AnyFn;
NameDesc
fnFunction to wrap
wrapperWrapper function
returnNew function
const p = wrap(escape, function(fn, text) {
    return '<p>' + fn(text) + '</p>';
});
p('You & Me'); // -> '<p>You &amp; Me</p>'

wx

source test1.4.6

Promised version of mini program wx object.

Type Definition
const wx: any;
wx.getStorage('test').then(res => {
    console.log(res.data);
});

xpath

source test1.10.0

Select elements using xpath, IE is not supported.

Type Definition
function xpath(xpath: string): HTMLElement[];
NameDesc
xpathXpath
returnTarget elements
xpath('//html/body'); // -> [body]

zip

source test1.0.0

Merge together the values of each of the arrays with the values at the corresponding position.

Type Definition
function zip(...arr: Array<any[]>): Array<any[]>;
NameDesc
arrArrays to process
returnNew array of grouped elements
zip(['a', 'b'], [1, 2], [true, false]); // -> [['a', 1, true], ['b', 2, false]]