English 中文

$

source test1.0.0

jQuery like style dom manipulator.

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.

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

NameTypeDesc
elementstring array elementElements to manipulate
namestringAttribute name
returnstringAttribute value of first element

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

NameTypeDesc
elementstring array elementElements to manipulate
namestringAttribute name
valuestringAttribute value
NameTypeDesc
elementstring array elementElements to manipulate
attributesobjectObject of attribute-value pairs to set

remove

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

NameTypeDesc
elementstring array elementElements to manipulate
namestringAttribute 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.

add

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

NameTypeDesc
elementstring array elementElements to manipulate
namesstring arrayClasses to add

has

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

NameTypeDesc
elementstring array elementElements to manipulate
namestringClass name
returnbooleanTrue 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.

NameTypeDesc
elementstring array elementElements to manipulate
namestringClass name to toggle

remove

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

NameTypeDesc
elementstring array elementElements to manipulate
namestringClass 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.

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

NameTypeDesc
elementstring array elementElements to manipulate
namestringProperty name
returnstringCss value of first element

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

NameTypeDesc
elementstring array elementElements to manipulate
namestringProperty name
valuestringCss value
NameTypeDesc
elementstring array elementElements to manipulate
propertiesobjectObject of css-value pairs to set
$css('#test', {
    color: '#fff',
    background: 'black'
});
$css('#test', 'display', 'block');
$css('#test', 'color'); // -> #fff

$data

source test1.0.0

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

$data('#test', 'attr1', 'eustia');

$event

source test1.0.0

bind events to certain dom elements.

function clickHandler() {
    // Do something...
}
$event.on('#test', 'click', clickHandler);
$event.off('#test', 'click', clickHandler);

$insert

source test1.0.0

Insert html on different position.

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.

NameTypeDesc
elementstring array elementElements to manipulate
contentstringHtml strings
// <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.

NameTypeDesc
elementstring array elementElements to get offset
$offset('#test'); // -> {left: 0, top: 0, width: 0, height: 0}

$property

source test1.0.0

Element property html, text, val getter and setter.

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.

NameTypeDesc
elementstring array elementElements to delete
$remove('#test');

$safeEls

source test1.0.0

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

NameTypeDesc
valueelement array stringValue to convert
returnarrayArray 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.

NameTypeDesc
elementstring array elementElements to show
$show('#test');

Blob

source test1.0.0

Use Blob when available, otherwise BlobBuilder.

constructor

NameTypeDesc
partsarrayBlob parts
[opts]objectOptions
const blob = new Blob([]);

Caseless

source test1.9.0

Modify object props without caring about letter case.

constructor

NameTypeDesc
objobjectTarget object

getKey

Get key with preserved casing.

NameTypeDesc
keystringCaseless key
returnstringObject key

set

Set value.

NameTypeDesc
keystringCaseless key
val*Value to set

get

Get value.

NameTypeDesc
keystringCaseless key
return*Value of given key

remove

Remove value.

NameTypeDesc
keystringCaseless key

has

Determine whether target object has given key.

NameTypeDesc
keystringCaseless key
returnbooleanTrue 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.

NameTypeDesc
methodsobjectPublic methods
[statics]objectStatic methods
returnfunctionFunction 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.

constructor

NameTypeDesc
colorstring objectColor 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.

NameTypeDesc
colorstringColor string
returnobjectObject 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%)'

Dispatcher

source test1.0.0

Flux dispatcher.

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.

on

Bind event.

off

Unbind event.

once

Bind event that trigger once.

NameTypeDesc
eventstringEvent name
listenerfunctionEvent listener

emit

Emit event.

NameTypeDesc
eventstringEvent name
...args*Arguments passed to listener

mixin

[static] Mixin object class methods.

NameTypeDesc
objobjectObject to mixin
const event = new Emitter();
event.on('test', function () { console.log('test') });
event.emit('test'); // Logs out 'test'.
Emitter.mixin({});

Enum

source test1.0.0

Enum type implementation.

constructor

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

JsonTransformer

source test1.0.0

Json to json transformer.

constructor

NameTypeDesc
[data={}]objectJson object to manipulate

set

Set object value.

NameTypeDesc
[key]stringObject key
val*Value to set

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

get

Get object value.

NameTypeDesc
[key]stringObject key
return*Specified value or whole object

remove

Remove object value.

NameTypeDesc
keyarray stringObject keys to remove

map

Shortcut for array map.

NameTypeDesc
fromstringFrom object path
tostringTarget object path
fnfunctionFunction invoked per iteration

filter

Shortcut for array filter.

compute

Compute value from several object values.

NameTypeDesc
fromarray stringSource values
tostringTarget object path
fnfunctionFunction 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.

size

List size.

head.

First node.

tail

Last node.

push

Add an value to the end of the list.

NameTypeDesc
val*Value to push
returnnumberCurrent 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.

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.

Extend from Store.

constructor

NameTypeDesc
namestringLocalStorage item name
dataobjectDefault data
const store = new LocalStore('licia');
store.set('name', 'licia');

Logger

source test demo1.0.0

Simple logger with level filter.

constructor

NameTypeDesc
namestringLogger name
level=DEBUGnumberLogger level

setLevel

Set level.

NameTypeDesc
levelnumber stringLogger 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.

constructor

NameTypeDesc
maxnumberMax items in cache

has

Check if has cache.

NameTypeDesc
keystringCache key

remove

Remove cache.

NameTypeDesc
keystringCache key

get

Get cache value.

NameTypeDesc
keystringCache key
return*Cache value

set

Set cache.

NameTypeDesc
keystringCache key
val*Cache 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.

Extend from Emitter.

constructor

NameTypeDesc
querystringMedia 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();

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.

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.

clear

Clear the queue.

enqueue

Add an item to the queue.

NameTypeDesc
item*Item to enqueue
returnnumberCurrent size

dequeue

Remove the first item of the queue.

peek

Get the first item without removing it.

forEach

Iterate over the queue.

NameTypeDesc
iteratorfunctionFunction invoked iteration
[ctx]*Function context

toArr

Convert queue to a JavaScript array.

const queue = new Queue();

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

QuickLru

source test benchmark1.4.5

LRU implementation without linked list.

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'

ReduceStore

source test1.0.0

Simplified redux like state container.

constructor

NameTypeDesc
reducerfunctionFunction returns next state
initialState*Initial state

subscribe

Add a change listener.

NameTypeDesc
listenerfunctionCallback to invoke on every dispatch
returnfunctionFunction to unsubscribe

dispatch

Dispatch an action.

NameTypeDesc
actionobjectObject representing changes
returnobjectSame 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

Select

source test1.0.0

Simple wrapper of querySelectorAll to make dom selection easier.

constructor

NameTypeDesc
selectorstringDom selector string

find

Get desdendants of current matched elements.

NameTypeDesc
selectorstringDom selector string

each

Iterate over matched elements.

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

SessionStore

source test1.0.0

SessionStorage wrapper.

Extend from Store.

constructor

NameTypeDesc
namestringSessionStorage item name
dataobjectDefault data
const store = new SessionStore('licia');
store.set('name', 'licia');

Stack

source test1.0.0

Stack data structure.

clear

Clear the stack.

push

Add an item to the stack.

NameTypeDesc
item*Item to add
returnnumberCurrent size

pop

Get the last item of the stack.

peek

Get the last item without removing it.

forEach

Iterate over the stack.

NameTypeDesc
iteratorfunctionFunction invoked iteration
[ctx]*Function context

toArr

Convert the stack to a JavaScript array.

const stack = new Stack();

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

State

source test1.0.0

Simple state machine.

Extend from Emitter.

constructor

NameTypeDesc
initialstringInitial state
eventsobjectEvents to change state

is

Check current state.

NameTypeDesc
valuestringState to check
returnbooleanTrue 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.

Extend from Emitter.

constructor

NameTypeDesc
dataobjectInitial data

set

Set value.

NameTypeDesc
keystringValue key
val*Value to set

Set values.

NameTypeDesc
valsobjectKey value pairs

This emit a change event whenever is called.

get

Get value.

NameTypeDesc
keystringValue key
return*Value of given key

Get values.

NameTypeDesc
keysarrayArray of keys
returnobjectKey value pairs

remove

Remove value.

NameTypeDesc
keystring arrayKey to remove

clear

Clear all data.

each

Iterate over values.

NameTypeDesc
fnfunctionFunction invoked per interation
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.
});

Tween

source test demo1.0.0

Tween engine for JavaScript animations.

Extend from Emitter.

constructor

NameTypeDesc
objobjectValues to tween

to

NameTypeDesc
destinationobjFinal properties
durationnumberTween duration
easestring functionEasing function

play

Begin playing forward.

pause

Pause the animation.

paused

Get animation paused state.

progress

Update or get animation progress.

NameTypeDesc
[progress]numberNumber 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.

constructor

NameTypeDesc
url=locationstringUrl string

setQuery

Set query value.

NameTypeDesc
namestringQuery name
valuestringQuery value
returnUrlthis
NameTypeDesc
queryobjectquery object
returnUrlthis

rmQuery

Remove query value.

NameTypeDesc
namestring arrayQuery name
returnUrlthis

parse

[static] Parse url into an object.

NameTypeDesc
urlstringUrl string
returnobjectUrl object

stringify

[static] Stringify url object into a string.

NameTypeDesc
urlobjectUrl object
returnstringUrl 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.

constructor

NameTypeDesc
optionsobjectValidation configuration

validate

Validate object.

NameTypeDesc
objobjectObject to validate
return*Validation result, true means ok

addPlugin

[static] Add plugin.

NameTypeDesc
namestringPlugin name
pluginfunctionValidation 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

abbrev

source test1.0.0

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

NameTypeDesc
...arrstringList of names
returnobjectAbbreviation 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.

NameTypeDesc
nnumberNumber of calls before invoked
fnfunctionFunction to restrict
returnfunctionNew 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.

NameTypeDesc
optionsobjectAjax options

Available options:

NameTypeDesc
type=gettypeRequest type
urlstringRequest url
datastring objectRequest data
dataType=jsonstringResponse type(json, xml)
contentType=application/x-www-form-urlencodedstringRequest header Content-Type
successfunctionSuccess callback
errorfunctionError callback
completefunctionCallback after request
timeoutnumberRequest timeout

get

Shortcut for type = GET;

post

Shortcut for type = POST;

NameTypeDesc
urlstringRequest url
[data]string objectRequest data
successfunctionSuccess callback
dataTypefunctionResponse 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.

NameTypeDesc
objobjectObject to query
[options]objectOptions
returnarrayArray of all property names

Available options:

NameTypeDesc
prototype=truebooleanInclude prototype keys
unenumerable=falsebooleanInclude unenumerable keys
symbol=falsebooleanInclude 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.

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.

NameTypeDesc
arrarrayArray of strings
val=true*Key value
returnobjectObject 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.

atob('SGVsbG8gV29ybGQ='); // -> 'Hello World'

average

source test1.0.0

Get average value of given numbers.

NameTypeDesc
...numnumberNumbers to calculate
returnnumberAverage value
average(5, 3, 1); // -> 3

base64

source test1.0.0

Basic base64 encoding and decoding.

encode

Turn a byte array into a base64 string.

NameTypeDesc
arrarrayByte array
returnstringBase64 string

decode

Turn a base64 string into a byte array.

NameTypeDesc
strstringBase64 string
returnarrayByte 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.

NameTypeDesc
nnumberNumber of calls at which fn is no longer invoked
fnfunctionFunction to restrict
returnfunctionNew 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.

NameTypeDesc
arrayarraySorted array
value*Value to seek
[comparator]functionComparator
returnnumberValue 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.

NameTypeDesc
fnfunctionFunction to bind
ctx*This binding of given fn
...rest*Optional arguments
returnfunctionNew 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.

btoa('Hello World'); // -> 'SGVsbG8gV29ybGQ='

bubbleSort

source test1.0.0

Bubble sort implementation.

NameTypeDesc
arrarrayArray to sort
[cmp]functionComparator
returnarraySorted array
bubbleSort([2, 1]); // -> [1, 2]

bytesToStr

source test1.1.0

Convert bytes to string.

NameTypeDesc
strarrayBytes array
returnstringResult string
bytesToStr([108, 105, 99, 105, 97]); // -> 'licia'

callbackify

source test1.0.0

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

NameTypeDesc
fnfunctionFunction that returns a Promise
returnfunctionFunction 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".

NameTypeDesc
strstringString to convert
returnstringCamel 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.

NameTypeDesc
strstringString to capitalize
returnstringCapitalized string
capitalize('rED'); // -> Red

castPath

source test1.0.0

Cast value into a property path array.

NameTypeDesc
pathstring arrayValue to inspect
[obj]objectObject to query
returnarrayProperty 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.

NameTypeDesc
strstring arrayString to align
[width]numberTotal width of each line
returnstringCenter aligned string
centerAlign('test', 8); // -> '  test'
centerAlign('test\nlines', 8); // -> '  test\n lines'
centerAlign(['test', 'lines'], 8); // -> '  test\n lines'

char

source test1.0.0

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

NameTypeDesc
numnumberInteger to convert
returnstringString representing corresponding char
char(65); // -> 'A'
char(97); // -> 'a'

chunk

source test1.0.0

Split array into groups the length of given size.

NameTypeDesc
arrarrayArray to process
size=1numberLength of each chunk
returnarrayChunks 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.

NameTypeDesc
nnumberNumber to clamp
[lower]numberLower bound
uppernumberUpper bound
returnnumberClamped 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.

NameTypeDesc
...classstring object arrayClass names
returnstringJoined 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';

clone

source test1.0.0

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

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

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

cloneDeep

source test1.0.0

Recursively clone value.

NameTypeDesc
val*Value to clone
return*Deep cloned Value
const obj = [{a: 1}, {a: 2}];
const obj2 = cloneDeep(obj);
console.log(obj[0] === obj2[1]); // -> false

cmpVersion

source test1.0.0

Compare version strings.

NameTypeDesc
v1stringVersion to compare
v2stringVersion to compare
returnnumberComparison 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.

NameTypeDesc
keysarrayKeys to be used
valuesarrayValues to be used
returnobjectCreated 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.

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

NameTypeDesc
arrarrayArray to compact
returnarrayNew array of filtered values
compact([0, 1, false, 2, '', 3]); // -> [1, 2, 3]

compose

source test1.0.0

Compose a list of functions.

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

NameTypeDesc
...fnfunctionFunctions to compose
returnfunctionComposed 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.

NameTypeDesc
fileFile Blob stringImage file or url
[opts]objectOptions
[cb]functionCallback

Available options:

NameTypeDesc
maxWidthnumberMax width
maxHeightnumberMax height
widthnumberOutput image width
heightnumberOutput image height
mimeTypestringMime type
quality=0.8numberImage 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.

NameTypeDesc
...arrarrayArrays to concat
returnarrayConcatenated 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.

NameTypeDesc
targetarray object stringTarget object
value*Value to check
returnbooleanTrue if value is present in the list
contain([1, 2, 3], 1); // -> true
contain({a: 1, b: 2}, 1); // -> true
contain('abc', 'a'); // -> true

convertBase

source test1.0.0

Convert base of a number.

NameTypeDesc
numnumber stringNumber to convert
fromnumberBase from
tonumberBase to
returnstringConverted number
convertBase('10', 2, 10); // -> '2'
convertBase('ff', 16, 2); // -> '11111111'

convertBin

source test1.5.0

Convert binary data type.

NameTypeDesc
bin*Binary data to convert
typestringBinary type
return*Target binary

Supported binary type

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

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

blobToArrBuffer

Convert Blob to ArrayBuffer.

NameTypeDesc
blobBlobBlob to convert
returnPromiseArrayBuffer 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.

get

Get cookie value.

NameTypeDesc
keystringCookie key
returnstringCorresponding cookie value

set

Set cookie value.

NameTypeDesc
keystringCookie key
valstringCookie value
[options]objectCookie options
returnexportsModule cookie

remove

Remove cookie value.

NameTypeDesc
keystringCookie key
[options]objectCookie options
returnexportsModule 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.

NameTypeDesc
textstringText to copy
[cb]functionOptional callback
copy('text', function (err) {
    // Handle errors.
});

crc1

source test1.5.7

CRC1 implementation.

NameTypeDesc
inputstring Buffer ArrayBuffer Uint8ArrayData to calculate
[previous]numberPrevious CRC1 result
returnnumberCRC1 result
crc1('1234567890').toString(16); // -> 'd'

crc16

source test1.5.9

CRC16 implementation.

NameTypeDesc
inputstring Buffer ArrayBuffer Uint8ArrayData to calculate
[previous]numberPrevious CRC16 result
returnnumberCRC16 result
crc16('1234567890').toString(16); // -> 'c57a'

crc32

source test1.5.9

CRC32 implementation.

NameTypeDesc
inputstring Buffer ArrayBuffer Uint8ArrayData to calculate
[previous]numberPrevious CRC32 result
returnnumberCRC16 result
crc32('1234567890').toString(16); // -> '261daee5'

crc8

source test1.5.9

CRC8 implementation.

NameTypeDesc
inputstring Buffer ArrayBuffer Uint8ArrayData to calculate
[previous]numberPrevious CRC8 result
returnnumberCRC8 result
crc8('1234567890').toString(16); // -> '52'

createAssigner

source test1.0.0

Used to create extend, extendOwn and defaults.

NameTypeDesc
keysFnfunctionFunction to get object keys
defaultsbooleanNo override when set to true
returnfunctionResult function, extend...

createUrl

source test1.0.0

CreateObjectURL wrapper.

NameTypeDesc
dataFile Blob string arrayUrl data
[opts]objectUsed when data is not a File or Blob
returnstringBlob url
createUrl('test', {type: 'text/plain'}); // -> Blob url
createUrl(['test', 'test']);
createUrl(new Blob([]));
createUrl(new File(['test'], 'test.txt'));

cssSupports

source test1.0.0

Check if browser supports a given CSS feature.

NameTypeDesc
namestringCss property name
[val]stringCss property value
returnbooleanTrue 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.

NameTypeDesc
fnfunctionFunction to curry
returnfunctionNew 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.

NameTypeDesc
date=new DateDateDate object to format
maskstringFormat mask
utc=falsebooleanUTC or not
gmt=falsebooleanGMT or not
MaskDescription
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.

NameTypeDesc
fnfunctionFunction to debounce
waitnumberNumber of milliseconds to delay
returnfunctionNew debounced function
const calLayout = debounce(function () {}, 300);
// $(window).resize(calLayout);

debug

source test demo1.0.0

A tiny JavaScript debugging utility.

NameTypeDesc
namestringNamespace
returnfunctionFunction 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.

NameTypeDesc
strstringString to deburr
returnstringDeburred string
deburr('déjà vu'); // -> 'deja vu'

decodeUriComponent

source test1.0.0

Better decodeURIComponent that does not throw if input is invalid.

NameTypeDesc
strstringString to decode
returnstringDecoded 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.

NameTypeDesc
objobjectDestination object
*srcobjectSources objects
returnobjectDestination 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.

NameTypeDesc
namestringModule name
[requires]arrayDependencies
methodfunctionModule 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).

NameTypeDesc
objobjectObject to define
propstringProperty path
descriptorobjectProperty descriptor
returnobjectObject itself
NameTypeDesc
objobjectObject to define
propobjectProperty descriptors
returnobjectObject 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

delRequireCache

source test1.5.4

Delete node.js require cache.

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

NameTypeDesc
fnfunctionFunction to delay
waitnumberNumber of milliseconds to delay invocation
[...args]*Arguments to invoke fn with
delay(function (text) {
    console.log(text);
}, 1000, 'later');
// -> Logs 'later' after one second

delegate

source test1.0.0

Event delegation.

add

Add event delegation.

NameTypeDesc
elelementParent element
typestringEvent type
selectorstringMatch selector
cbfunctionEvent 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.

NameTypeDesc
fnfunctionFunction to be deprecated
msgstringWarning message
returnfunctionDeprecated function
const fn = () => {};
const obsoleteFn = deprecate(fn, 'obsoleteFn is deprecated.');
obsoleteFn();

detectBrowser

source test1.0.0

Detect browser info using ua.

NameTypeDesc
ua=navigator.userAgentstringBrowser userAgent
returnobjectObject 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.

detectMocha(); // -> True if mocha is running.

detectOs

source test1.0.0

Detect operating system using ua.

NameTypeDesc
ua=navigator.userAgentstringBrowser userAgent
returnstringOperating 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.

NameTypeDesc
arrarrayArray to inspect
[...rest]arrayValues to exclude
returnarrayNew array of filtered values
difference([3, 2, 1], [4, 2]); // -> [3, 1]

dotCase

source test1.0.0

Convert string to "dotCase".

NameTypeDesc
strstringString to convert
returnstringDot cased string
dotCase('fooBar'); // -> foo.bar
dotCase('foo bar'); // -> foo.bar

download

source test demo1.0.0

Trigger a file download on client side.

NameTypeDesc
dataBlob File string arrayData to download
namestringFile name
type=text/plainstringData type
download('test', 'test.txt');

each

source test benchmark1.0.0

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

NameTypeDesc
objobject arrayCollection to iterate over
iteratorfunctionFunction invoked per iteration
[ctx]*Function context
each({'a': 1, 'b': 2}, function (val, key) {});

easing

source test1.0.0

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

NameTypeDesc
percentnumberNumber between 0 and 1
returnnumberCalculated 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.

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

NameTypeDesc
strstringThe string to search
suffixstringString suffix
returnbooleanTrue if string ends with target
endWith('ab', 'b'); // -> true

escape

source test1.0.0

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

NameTypeDesc
strstringString to escape
returnstringEscaped string
escape('You & Me'); // -> 'You &amp; Me'

escapeJsStr

source test1.0.0

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

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

NameTypeDesc
strstringString to escape
returnstringEscaped string
escapeJsStr('\"\n'); // -> '\\"\\\\n'

escapeRegExp

source test1.0.0

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

NameTypeDesc
strstringString to escape
returnstringEscaped string
escapeRegExp('[licia]'); // -> '\\[licia\\]'

evalCss

source test1.0.0

Load css into page.

NameTypeDesc
cssstringCss code
evalCss('body{background:#08c}');

evalJs

source test benchmark1.0.0

Execute js in given context.

NameTypeDesc
jsstringJavaScript code
ctx=globalobjectContext
evalJs('5+2'); // -> 7
evalJs('this.a', {a: 2}); // -> 2

every

source test1.0.0

Check if predicate return truthy for all elements.

NameTypeDesc
objectarray objectCollection to iterate over
[iterator]functionFunction invoked per iteration
[context]*Predicate context
returnbooleanTrue if all elements pass the predicate check
every([2, 4], function (val) {
    return val % 2 === 0;
}); // -> false

extend

source test1.0.0

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

NameTypeDesc
destinationobjectDestination object
...sourcesobjectSources objects
returnobjectDestination object
extend({name: 'RedHood'}, {age: 24}); // -> {name: 'RedHood', age: 24}

extendDeep

source test1.0.0

Recursive object extending.

NameTypeDesc
destinationobjectDestination object
...sourcesobjectSources objects
returnobjectDestination 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.

NameTypeDesc
destinationobjectDestination object
...sourcesobjectSources objects
returnobjectDestination object
extendOwn({name: 'RedHood'}, {age: 24}); // -> {name: 'RedHood', age: 24}

extractBlockCmts

source test1.0.0

Extract block comments from source code.

NameTypeDesc
strstringString to extract
returnarrayBlock comments
extractBlockCmts('\/*licia*\/'); // -> ['licia']

extractUrls

source test1.0.0

Extract urls from plain text.

NameTypeDesc
strstringText to extract
returnarrayUrl 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.

Note: This is not a complete fetch pollyfill.

NameTypeDesc
urlstringRequest url
[options]objectRequest options
returnPromiseRequest 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.

NameTypeDesc
nnumberIndex of fibonacci sequence
returnnumberExpected fibonacci number
fibonacci(1); // -> 1
fibonacci(3); // -> 2

fileSize

source test1.0.0

Turn bytes into human readable file size.

NameTypeDesc
bytesnumberFile bytes
returnstringReadable 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.

NameTypeDesc
inputBuffer ArrayBuffer Uint8ArrayFile input
returnobject nullObject 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' }

fill

source test1.0.0

Fill elements of array with value.

NameTypeDesc
listarrayArray to fill
value*Value to fill array with
start=0numberStart position
end=arr.lengthnumberEnd position
returnarrayFilled 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.

NameTypeDesc
objarrayCollection to iterate over
predicatefunctionFunction invoked per iteration
[ctx]*Predicate context
returnarrayArray 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.

NameTypeDesc
objectarray objectCollection to iterate over
iteratorfunctionFunction invoked per iteration
[context]*Predicate context
return*First value that passes predicate
find([{
    name: 'john',
    age: 24
}, {
    name: 'jane',
    age: 23
}], function (val) {
    return val.age === 23;
}); // -> {name: 'jane', age: 23}

findIdx

source test1.0.0

Return the first index where the predicate truth test passes.

NameTypeDesc
arrarrayArray to search
predicatefunctionFunction invoked per iteration
returnnumberIndex 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.

NameTypeDesc
objobjectObject to search
predicatefunctionFunction invoked per iteration
[ctx]*Predicate context
returnstringKey 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.

NameTypeDesc
arrarrayArray to search
predicatefunctionFunction invoked per iteration
returnnumberLast 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.

NameTypeDesc
arrarrayArray to flatten
returnarrayNew flattened array
flatten(['a', ['b', ['c']], 'd', ['e']]); // -> ['a', 'b', 'c', 'd', 'e']

fnArgs

source test1.5.3

Validate function arguments.

NameTypeDesc
typesarrayArgument types
argsArgumentArgument 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.

NameTypeDesc
fnfunction stringFunction to get parameters
returnarrayNames
fnParams(function (a, b) {}); // -> ['a', 'b']

format

source test1.0.0

Format string in a printf-like format.

NameTypeDesc
strstringString to format
...values*Values to replace format specifiers
returnstringFormatted 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.

NameTypeDesc
numnumberNumber to convert
returnstringCorresponding fraction
fraction(1.2); // -> '6/5'

freeze

source test1.0.0

Shortcut for Object.freeze.

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

NameTypeDesc
objobjectObject to freeze
returnobjectObject 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.

NameTypeDesc
objobjectObject to freeze
returnobjectObject 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.

fs.readFile('test.js').then(function (data) {
    // Do something
}).catch(function (err) {
    // Handle errors
});

fullscreen

source test demo1.4.0

Fullscreen api wrapper.

request

Request fullscreen.

NameTypeDesc
[el]ElementFullscreen element

exit

Exit fullscreen.

toggle

Toggle fullscreen.

NameTypeDesc
[el]ElementFullscreen 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.

NameTypeDesc
needlestringString to search
haystacksarraySearch list
[options]objectSearch options

Available options:

NameTypeDesc
caseSensitive=falsebooleanWhether comparisons should be case sensitive
[key]string arrayObject 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.

NameTypeDesc
anumberNumber to calculate
bnumberNumber to calculate
returnnumberGreatest common divisor
gcd(121, 44); // -> 11

getPort

source test1.1.0

Get an available TCP port.

NameTypeDesc
[port]number arrayPreferred ports
[host]stringHost address
returnPromiseAvailable 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.

NameTypeDesc
obj*Target object
return*Prototype of given object, null if not exists
const a = {};
getProto(Object.create(a)); // -> a

getUrlParam

source test1.0.0

Get url param.

NameTypeDesc
namestringParam name
url=locationstringUrl to get param
returnstringParam value
getUrlParam('test', 'http://example.com/?test=true'); // -> 'true'

golangify

source test1.5.4

Handle errors like golang.

NameTypeDesc
fnfunctionFunction that returns a Promise
returnfunctionLike fn, but resolves with [result, error]
NameTypeDesc
pPromisePromise to transform
returnPromisePromise 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.

NameTypeDesc
tagstringTag name
[attrs]objectAttributes
[...child]string HTMLElementChildren
returnHTMLElementCreated 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.

NameTypeDesc
objobjectObject to query
keystringPath to check
returnbooleanTrue if key is a direct property
has({one: 1}, 'one'); // -> true

highlight

source test demo1.5.6

Highlight code.

NameTypeDesc
strstringCode string
lang=jsstringLanguage, js, html or css
[style]objectKeyword highlight style
returnstringHighlighted html code string

Available styles:

comment, string, number, keyword, operator

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

hotkey

source test demo1.0.0

Capture keyboard input to trigger given events.

on

Register keyboard listener.

NameTypeDesc
keystringKey string
listenerfunctionKey listener

off

Unregister keyboard listener.

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

hslToRgb

source test1.0.0

Convert hsl to rgb.

NameTypeDesc
hslarrayHsl values
returnarrayRgb values
hslToRgb([165, 59, 50, 0.8]); // -> [52, 203, 165, 0.8]

html

source test1.6.0

Html parser and serializer.

parse

Parse html string into js object.

NameTypeDesc
htmlstringHtml string
returnarrayParsed js object

stringify

Stringify object into an html string.

NameTypeDesc
treearrayObject to stringify
returnstringHtml 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.

NameTypeDesc
val*Any value
return*Given value
identity('a'); // -> 'a'

idxOf

source test1.0.0

Get the index at which the first occurrence of value.

NameTypeDesc
arrarrayArray to search
val*Value to search for
fromIdx=0numberIndex to search from
returnnumberValue index
idxOf([1, 2, 1, 2], 2, 2); // -> 3

indent

source test1.0.0

Indent each line in a string.

NameTypeDesc
strstringString to indent
[char]stringCharacter to prepend
[len]numberIndent length
returnstringIndented string
indent('foo\nbar', ' ', 4); // -> '    foo\n    bar'

inherits

source test1.0.0

Inherit the prototype methods from one constructor into another.

NameTypeDesc
ClassfunctionChild Class
SuperClassfunctionSuper 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.

parse

Parse ini string into js object.

NameTypeDesc
inistringIni string
returnobjectParsed js object

stringify

Stringify object into an ini formatted string.

NameTypeDesc
obj*Object to stringify
optionsobjectStringify options
returnstringIni formatted string

Options:

NameTypeDesc
[section]stringTop section
whitespace=falsebooleanWhitespace 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.

NameTypeDesc
arrarrayArray to sort
[cmp]functionComparator
returnarraySorted array
insertionSort([2, 1]); // -> [1, 2]

intersect

source test1.0.0

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

NameTypeDesc
...arrarrayArrays to inspect
returnarrayNew array of inspecting values
intersect([1, 2, 3, 4], [2, 1, 10], [2, 1]); // -> [1, 2]

intersectRange

source test1.0.0

Intersect two ranges.

NameTypeDesc
aobjectRange a
bobjectRange b
returnobjectIntersection 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

invert

source test1.0.0

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

NameTypeDesc
objobjectObject to invert
returnobjectNew 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.

NameTypeDesc
urlstringUrl to check
returnbooleanTrue 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.

NameTypeDesc
val*Value to check
returnbooleanTrue if value is an arguments object
(function () {
    isArgs(arguments); // -> true
})();

isArr

source test1.0.0

Check if value is an Array object.

NameTypeDesc
val*Value to check
returnbooleanTrue if value is an Array object
isArr([]); // -> true
isArr({}); // -> false

isArrBuffer

source test1.0.0

Check if value is an ArrayBuffer.

NameTypeDesc
val*Value to check
returnbooleanTrue if value is an ArrayBuffer
isArrBuffer(new ArrayBuffer(8)); // -> true

isArrLike

source test1.0.0

Check if value is array-like.

NameTypeDesc
val*Value to check
returnbooleanTrue if value is array like

Function returns false.

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

isBlob

source test1.0.0

Check if value is a Blob.

NameTypeDesc
val*Value to check
returnbooleanTrue if value is a Blob
isBlob(new Blob([])); // -> true;
isBlob([]); // -> false

isBool

source test1.0.0

Check if value is a boolean primitive.

NameTypeDesc
val*Value to check
returnbooleanTrue 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.

console.log(isBrowser); // -> true if running in a browser

isBuffer

source test1.0.0

Check if value is a buffer.

NameTypeDesc
val*The value to check
returnbooleanTrue 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.

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

NameTypeDesc
anumberNumber to compare
bnumberNumber to compare
relTol=1e-9numberRelative tolerance
absTol=0numberAbsolute tolerance
returnbooleanTrue 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

isDataUrl

source test1.0.0

Check if a string is a valid data url.

NameTypeDesc
strstringString to check
returnbooleanTrue 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.

NameTypeDesc
val*value to check
returnbooleanTrue if value is a Date object
isDate(new Date()); // -> true

isEl

source test1.0.0

Check if value is a DOM element.

NameTypeDesc
val*Value to check
returnbooleanTrue if value is a DOM element
isEl(document.body); // -> true

isEmail

source test1.0.0

Loosely validate an email address.

NameTypeDesc
valstringValue to check
returnbooleanTrue if value is an email like string
isEmail('surunzi@foxmail.com'); // -> true

isEmpty

source test1.0.0

Check if value is an empty object or array.

NameTypeDesc
val*Value to check
returnbooleanTrue 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.

NameTypeDesc
val*Value to compare
other*Other value to compare
returnbooleanTrue if values are equivalent
isEqual([1, 2, 3], [1, 2, 3]); // -> true

isErr

source test1.0.0

Check if value is an error.

NameTypeDesc
val*Value to check
returnbooleanTrue if value is an error
isErr(new Error()); // -> true

isEven

source test1.0.0

Check if number is even.

NameTypeDesc
numnumberNumber to check
returnbooleanTrue if number is even
isEven(0); // -> true
isEven(1); // -> false
isEven(2); // -> true

isFile

source test1.0.0

Check if value is a file.

NameTypeDesc
val*Value to check
returnbooleanTrue 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.

NameTypeDesc
val*Value to check
returnbooleanTrue if value is a finite number
isFinite(3); // -> true
isFinite(Infinity); // -> false

isFn

source test1.0.0

Check if value is a function.

NameTypeDesc
val*Value to check
returnbooleanTrue if value is a function

Generator function is also classified as true.

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

isGeneratorFn

source test1.0.0

Check if value is a generator function.

NameTypeDesc
val*Value to check
returnbooleanTrue if value is a generator function
isGeneratorFn(function * () {}); // -> true;
isGeneratorFn(function () {}); // -> false;

isInt

source test1.0.0

Checks if value is classified as a Integer.

NameTypeDesc
val*Value to check
returnbooleanTrue 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.

NameTypeDesc
strstringString to check
returnbooleanTrue 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.

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

NameTypeDesc
valstringJSON string
returnbooleanTrue 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.

NameTypeDesc
yearnumberYear to check
returnbooleanTrue if year is a leap year
isLeapYear(2000); // -> true
isLeapYear(2002); // -> false

isMap

source test1.0.0

Check if value is a Map object.

NameTypeDesc
val*Value to check
returnbooleanTrue 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.

NameTypeDesc
objobjectObject to inspect
srcobjectObject of property values to match
returnbooleanTrue if object is match
isMatch({a: 1, b: 2}, {a: 1}); // -> true

isMiniProgram

source test1.0.0

Check if running in wechat mini program.

console.log(isMiniProgram); // -> true if running in mini program.

isMobile

source test1.0.0

Check whether client is using a mobile browser using ua.

NameTypeDesc
ua=navigator.userAgentstringUser agent
returnbooleanTrue if ua belongs to mobile browsers
isMobile(navigator.userAgent);

isNaN

source test1.0.0

Check if value is an NaN.

NameTypeDesc
val*Value to check
returnbooleanTrue 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.

NameTypeDesc
val*Value to check
returnbooleanTrue 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.

NameTypeDesc
val*Value to check
returnbooleanTrue 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.

console.log(isNode); // -> true if running in node

isNull

source test1.0.0

Check if value is an Null.

NameTypeDesc
val*Value to check
returnbooleanTrue if value is an Null
isNull(null); // -> true

isNum

source test1.0.0

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

NameTypeDesc
val*Value to check
returnbooleanTrue if value is correctly classified
isNum(5); // -> true
isNum(5.1); // -> true
isNum({}); // -> false

isNumeric

source test1.0.0

Check if value is numeric.

NameTypeDesc
val*Value to check
returnbooleanTrue 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.

NameTypeDesc
val*Value to check
returnbooleanTrue if value is an object

Language Spec

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

isOdd

source test1.0.0

Check if number is odd.

NameTypeDesc
numnumberNumber to check
returnbooleanTrue 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.

NameTypeDesc
val*Value to check
returnbooleanTrue 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.

NameTypeDesc
portnumberTCP port
[host]stringHost address
returnPromiseTrue 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.

NameTypeDesc
numnumberNumber to check
returnbooleanTrue 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.

NameTypeDesc
val*Value to check
returnbooleanTrue 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.

NameTypeDesc
val*Value to check
returnbooleanTrue 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.

NameTypeDesc
val*Value to check
returnbooleanTrue if value is a regular expression
isRegExp(/a/); // -> true

isRelative

source test1.0.0

Check if path appears to be relative.

NameTypeDesc
pathstringPath to check
returnbooleanTrue 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.

console.log(isRetina); // -> true if high DPR

isSet

source test1.0.0

Check if value is a Set object.

NameTypeDesc
val*Value to check
returnbooleanTrue if value is a Set
isSet(new Set()); // -> true
isSet(new WeakSet()); // -> false

isSorted

source test1.0.0

Check if an array is sorted.

NameTypeDesc
arrarrayArray to check
[cmp]functionComparator
returnbooleanTrue 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.

NameTypeDesc
val*Value to check
returnbooleanTrue if value is a string primitive
isStr('licia'); // -> true

isStream

source test1.0.0

Check if value is a Node.js stream.

NameTypeDesc
val*Value to check
returnbooleanTrue 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.

NameTypeDesc
val*Value to check
returnbooleanTrue if value is a symbol
isSymbol(Symbol('test')); // -> true

isTypedArr

source test1.0.0

Check if value is a typed array.

NameTypeDesc
val*Value to check
returnbooleanTrue if value is a typed array
isTypedArr([]); // -> false
isTypedArr(new Uint8Array(8)); // -> true

isUndef

source test1.0.0

Check if value is undefined.

NameTypeDesc
val*Value to check
returnbooleanTrue if value is undefined
isUndef(void 0); // -> true
isUndef(null); // -> false

isUrl

source test1.0.0

Loosely validate an url.

NameTypeDesc
valstringValue to check
returnbooleanTrue 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.

NameTypeDesc
val*Value to check
returnbooleanTrue 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.

NameTypeDesc
val*Value to check
returnbooleanTrue if value is a WeakSet
isWeakSet(new Set()); // -> false
isWeakSet(new WeakSet()); // -> true

isWindows

source test1.0.0

Check if platform is windows.

console.log(isWindows); // -> true if running on windows

jsonp

source test1.0.0

A simple jsonp implementation.

NameTypeDesc
optsobjectJsonp Options

Available options:

NameTypeDesc
urlstringRequest url
dataobjectRequest data
successfunctionSuccess callback
param=callbackstringCallback param
[name]stringCallback name
errorfunctionError callback
completefunctionCallback after request
timeoutnumberRequest timeout
jsonp({
    url: 'http://example.com',
    data: {test: 'true'},
    success: function (data) {
        // ...
    }
});

kebabCase

source test1.0.0

Convert string to "kebabCase".

NameTypeDesc
strstringString to convert
returnstringKebab 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.

Get key code's name.

NameTypeDesc
codenumberKey code
returnstringCorresponding key name

Get key name's code.

NameTypeDesc
namestringKey name
returnnumberCorresponding key code
keyCode(13); // -> 'enter'
keyCode('enter'); // -> 13

keys

source test1.0.0

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

NameTypeDesc
objobjectObject to query
returnarrayArray of property names
keys({a: 1}); // -> ['a']

kill

source test1.4.4

Kill process.

NameTypeDesc
pidnumberProcess ID
kill(9420);

last

source test1.0.0

Get the last element of array.

NameTypeDesc
arrarrayThe array to query
return*The last element of array
last([1, 2]); // -> 2

lazyRequire

source test1.0.0

Require modules lazily.

const r = lazyRequire(require);

const _ = r('underscore');

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

levenshtein

source test1.4.8

Levenshtein distance implementation.

NameTypeDesc
astringFirst string
bstringSecond string
returnnumberLevenshtein distance between a and b
levenshtein('cat', 'cake'); // -> 2

linkify

source test1.0.0

Hyperlink urls in a string.

NameTypeDesc
strstringString to hyperlink
[hyperlink]functionFunction to hyperlink url
returnstringResult 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.

NameTypeDesc
srcstringStyle source
[cb]functionOnload callback
loadCss('style.css', function (isLoaded) {
    // Do something...
});

loadImg

source test1.0.0

Load image with given src.

NameTypeDesc
srcstringImage source
[cb]functionOnload 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.

NameTypeDesc
srcstringScript source
cbfunctionOnload callback
loadJs('main.js', function (isLoaded) {
    // Do something...
});

longest

source test1.0.0

Get the longest item in an array.

NameTypeDesc
arrarrayArray to inspect
return*Longest item
longest(['a', 'abcde', 'abc']); // -> 'abcde'

lowerCase

source test1.0.0

Convert string to lower case.

NameTypeDesc
strstringString to convert
returnstringLower cased string
lowerCase('TEST'); // -> 'test'

lpad

source test1.0.0

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

NameTypeDesc
strstringString to pad
lennumberPadding length
[chars]stringString used as padding
returnstringResult 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.

NameTypeDesc
strstringString to trim
[chars]string arrayCharacters to trim
returnstringTrimmed 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.

NameTypeDesc
objectarray objectCollection to iterate over
iteratorfunctionFunction invoked per iteration
[context]*Function context
returnarrayNew mapped array
map([4, 8], function (n) { return n * n; }); // -> [16, 64]

mapObj

source test1.0.0

Map for objects.

NameTypeDesc
objectobjectObject to iterate over
iteratorfunctionFunction invoked per iteration
[context]*Function context
returnobjectNew 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.

NameTypeDesc
attrsobjectObject of property values to match
returnfunctionNew 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.

NameTypeDesc
...numnumberNumbers to calculate
returnnumberMaximum value
max(2.3, 1, 4.5, 2); // 4.5

md5

source test1.1.0

MD5 implementation.

NameTypeDesc
msgstringMessage to encrypt
returnstringMD5 hash
md5('licia'); // -> 'e59f337d85e9a467f1783fab282a41d0'

memStorage

source test1.0.0

Memory-backed implementation of the Web Storage API.

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.

NameTypeDesc
fnfunctionFunction to have its output memoized
[hashFn]functionFunction to create cache key
returnfunctionNew memoized function
const fibonacci = memoize(function(n) {
    return n < 2 ? n : fibonacci(n - 1) + fibonacci(n - 2);
});

mergeSort

source test1.0.0

Merge sort implementation.

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

NameTypeDesc
arrarrayArray to sort
[cmp]functionComparator
returnarraySorted array
mergeSort([2, 1]); // -> [1, 2]

meta

source test1.0.0

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

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

NameTypeDesc
[name]string arrayMeta name
returnstringMeta content

Set meta content.

NameTypeDesc
namestringMeta name
contentstringMeta content
NameTypeDesc
metasobjectObject of name content pairs

remove

Remove metas.

NameTypeDesc
namestring arrayMeta 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.

NameTypeDesc
objobjectObject to check
returnarrayFunction names in object
methods(console); // -> ['Console', 'assert', 'dir', ...]

mime

source test1.5.0

Common mime types.

NameTypeDesc
namestringExtension
returnstring nullMime type
NameTypeDesc
namestringMime type
returnstring nullExtension

It contains only the most common file types.

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

min

source test1.0.0

Get minimum value of given numbers.

NameTypeDesc
...numnumberNumbers to calculate
returnnumberMinimum value
min(2.3, 1, 4.5, 2); // 1

mkdir

source test1.0.0

Recursively create directories.

NameTypeDesc
dirstringDirectory to create
mode=0777numberDirectory mode
[callback]functionCallback
mkdir('/tmp/foo/bar/baz', function (err) {
    if (err) console.log(err);
    else console.log('Done');
});

moment

source test1.0.0

Tiny moment.js like implementation.

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'

ms

source test1.0.0

Convert time string formats to milliseconds.

Turn time string into milliseconds.

NameTypeDesc
strstringString format
returnnumberMilliseconds

Turn milliseconds into time string.

NameTypeDesc
numnumberMilliseconds
returnstringString 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'

negate

source test1.0.0

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

NameTypeDesc
predicatefunctionPredicate to negate
returnfunctionNew function
function even(n) { return n % 2 === 0 }
// filter([1, 2, 3, 4, 5, 6], negate(even)); -> [1, 3, 5]

nextTick

source test1.0.0

Next tick for both node and browser.

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

noop(); // Does nothing

normalizeHeader

source test1.2.0

Normalize http header name.

NameTypeDesc
headerstringHeader to normalize
returnstringNormalized header
normalizeHeader('content-type'); // -> 'Content-Type'
normalizeHeader('etag'); // -> 'ETag'

normalizePath

source test1.0.0

Normalize file path slashes.

NameTypeDesc
pathstringPath to normalize
returnstringNormalized path
normalizePath('\\foo\\bar\\'); // -> '/foo/bar/'
normalizePath('./foo//bar'); // -> './foo/bar'

now

source test1.0.0

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

now(); // -> 1468826678701

objToStr

source test1.0.0

Alias of Object.prototype.toString.

NameTypeDesc
val*Source value
returnstringString representation of given value
objToStr(5); // -> '[object Number]'

omit

source test1.0.0

Opposite of pick.

NameTypeDesc
objobjectSource object
filterstring array functionObject filter
returnobjectFiltered 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.

NameTypeDesc
fnfunctionFunction to restrict
returnfunctionNew restricted function
function init() {};
const initOnce = once(init);
initOnce();
initOnce(); // -> init is invoked once

open

source test1.2.0

Open stuff like url, files.

NameTypeDesc
targetstringStuff to open
returnChildProcessChild process
open('https://eustia.liriliri.io/');

openFile

source test demo1.3.0

Open file dialog to select file in browser.

NameTypeDesc
optionsobjectDialog options
returnPromiseFiles promise

Available options:

NameTypeDesc
acceptstringFile types
multiple=falsebooleanSelect multiple files or not
openFile({multiple: true}).then(fileList => {
    console.log(fileList)
});

optimizeCb

source test1.0.0

Used for function context binding.

ordinal

source test1.5.2

Add ordinal indicator to number.

NameTypeDesc
numnumberNumber to add indicator
returnstringResult ordinal number
ordinal(1); // -> '1st'
ordinal(2); // -> '2nd'

orientation

source test demo1.0.0

Screen orientation helper.

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.

NameTypeDesc
strstringString to pad
lennumberPadding length
charsstringString used as padding
returnstringResult 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.

NameTypeDesc
objobjectObject to convert
returnarrayList 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.

NameTypeDesc
tasksarrayArray of functions
[cb]functionCallback 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.

NameTypeDesc
argsarrayArgument array
optsobjectParse options
returnobjectParsed result

options

NameTypeDesc
namesobjectoption names
shorthandsobjectoption 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.

NameTypeDesc
htmlstringHtml to parse
handlerobjectHandlers
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.

NameTypeDesc
fnfunctionFunction to partially apply arguments to
...partials*Arguments to be partially applied
returnfunctionNew 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".

NameTypeDesc
strstringString to convert
returnstringPascal 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.

const start = perfNow();

// Do something.

console.log(perfNow() - start);

pick

source test1.0.0

Return a filtered copy of an object.

NameTypeDesc
objectobjectSource object
filterstring array functionObject filter
returnobjectFiltered 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}

pluck

source test1.0.0

Extract a list of property values.

NameTypeDesc
objobject arrayCollection to iterate over
keystring arrayProperty path
returnarrayNew 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.

NameTypeDesc
numnumberNumber to check
returnnumberPrecision
precision(1.234); // -> 3;

prefetch

source test demo1.4.0

Fetch a given url.

NameTypeDesc
urlstringUrl to prefetch
returnPromiseA Promise

It uses <link rel=prefetch> if possible.

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

prefix

source test1.0.0

Add vendor prefixes to a CSS attribute.

NameTypeDesc
namestringProperty name
returnstringPrefixed 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.

NameTypeDesc
fnfunctionCallback based function
multiArgs=falsebooleanIf callback has multiple success value
returnfunctionResult 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.

NameTypeDesc
pathstring arrayPath of the property to get
returnfunctionNew 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.

parse

Parse a query string into an object.

NameTypeDesc
strstringQuery string
returnobjectQuery object

stringify

Stringify an object into a query string.

NameTypeDesc
objobjectQuery object
returnstringQuery 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.

NameTypeDesc
arrarrayArray to sort
[cmp]functionComparator
returnarraySorted array
quickSort([2, 1]); // -> [1, 2]

raf

source test1.0.0

Shortcut for requestAnimationFrame.

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

NameTypeDesc
minnumberMinimum possible value
maxnumberMaximum possible value
floating=falsebooleanFloat or not
returnnumberRandom 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.

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

NameTypeDesc
sizenumberNumber of bytes to generate
returnobjectRandom bytes of given length
randomBytes(5); // -> [55, 49, 153, 30, 122]

randomId

source test1.4.8

A tiny id generator, similar to nanoid.

NameTypeDesc
size=21numberId size
symbolsstringSymbols 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.

NameTypeDesc
arrarrayArray to get
return*Randomly picked item
randomItem([1, 2, 3]); // -> 2

range

source test1.0.0

Create flexibly-numbered lists of integers.

NameTypeDesc
[start]numberStart of the range
endnumberEnd of the range
step=1numberValue to increment or decrement by
returnarrayList 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.

encrypt

RC4 encryption, result as base64 string.

decrypt

RC4 decryption, pass base64 string as input.

NameTypeDesc
keystringSecret key
strstringString to be encrypted/decrypted
returnstringEncrypted/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.

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

NameTypeDesc
objobject arrayCollection to iterate over
iterator=identityfunctionFunction invoked per iteration
[initial]*Initial value
[ctx]*Function context
return*Accumulated value
reduce([1, 2, 3], function (sum, n) { return sum + n }, 0); // -> 6

reduceRight

source test1.0.0

Right-associative version of reduce.

reduceRight([[1], [2], [3]], function (a, b) { return a.concat(b) }, []); // -> [3, 2, 1]

reject

source test1.0.0

Opposite of filter.

NameTypeDesc
objarrayCollection to iterate over
predicatefunctionFunction invoked per iteration
[ctx]*Predicate context
returnarrayArray 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.

Unlike filter, this method mutates array.

NameTypeDesc
listarrayCollection to iterate over
iteratorfunctionFunction invoked per iteration
[context]*Predicate context
returnarrayArray 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.

NameTypeDesc
strstringString to repeat
nnumberRepeat times
returnstringRepeated string
repeat('a', 3); // -> 'aaa'
repeat('ab', 2); // -> 'abab'
repeat('*', 0); // -> ''

restArgs

source test1.0.0

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

NameTypeDesc
functionfunctionFunction that needs rest parameters
[startIndex]numberThe start index to accumulates
returnfunctionGenerated function with rest parameters
const paramArr = restArgs(function (rest) { return rest });
paramArr(1, 2, 3, 4); // -> [1, 2, 3, 4]

rgbToHsl

source test1.0.0

Convert rgb to hsl.

NameTypeDesc
rgbarrayRgb values
returnarrayHsl values
rgbToHsl([52, 203, 165, 0.8]); // -> [165, 59, 50, 0.8]

ric

source test1.4.0

Shortcut for requestIdleCallback.

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.

NameTypeDesc
keystringCookie key
rmCookie('test');

rmdir

source test1.0.0

Recursively remove directories.

NameTypeDesc
dirstringDirectory to remove
callbackfunctionCallback
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.

rpad

source test1.0.0

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

NameTypeDesc
strstringString to pad
lennumberPadding length
charsstringString used as padding
returnstringResult 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.

NameTypeDesc
strstringString to trim
[chars]string arrayCharacters to trim
returnstringTrimmed string
rtrim(' abc  '); // -> ' abc'
rtrim('_abc_', '_'); // -> '_abc'
rtrim('_abc_', ['c', '_']); // -> '_ab'

safeCb

source test1.0.0

Create callback based on input value.

safeDel

source test1.0.0

Delete object property.

NameTypeDesc
objobjectObject to query
patharray stringPath of property to delete
return*Deleted 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.

NameTypeDesc
objobjectObject to query
patharray stringPath of property to get
return*Target 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.

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

NameTypeDesc
objobjectObject to modify
patharray stringPath of property to set
val*Value 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.

NameTypeDesc
type='local'stringlocal or session
returnobjectSpecified storage
const localStorage = safeStorage('local');
localStorage.setItem('licia', 'util');

sample

source test1.0.0

Sample random values from a collection.

NameTypeDesc
objarray objectCollection to sample
nnumberNumber of values
returnarrayArray 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.

NameTypeDesc
targetelement string numberScroll target
optionsobjectScroll options

Options

NameTypeDefaultDesc
tolerancenumber0Tolerance of target to scroll
durationnumber800Scroll duration
easingstring functionoutQuartEasing function
callbackfunctionnoopFunction to run once scrolling complete
scrollTo('body', {
    tolerance: 0,
    duration: 800,
    easing: 'outQuart',
    callback: function () {}
});

selectionSort

source test1.0.0

Selection sort implementation.

NameTypeDesc
arrarrayArray to sort
[cmp]functionComparator
returnarraySorted array
selectionSort([2, 1]); // -> [1, 2]

shellSort

source test1.5.0

Shell sort implementation.

NameTypeDesc
arrarrayArray to sort
[cmp]functionComparator
returnarraySorted array
shellSort([2, 1]); // -> [1, 2]

shuffle

source test1.0.0

Randomize the order of the elements in a given array.

NameTypeDesc
arrarrayArray to randomize
returnarrayRandomized Array
shuffle([1, 2, 3]); // -> [3, 1, 2]

size

source test1.0.0

Get size of object or length of array like object.

NameTypeDesc
objarray objectCollection to inspect
returnnumberCollection size
size({a: 1, b: 2}); // -> 2
size([1, 2, 3]); // -> 3

sleep

source test1.4.1

Resolve a promise after a specified timeout.

NameTypeDesc
timeoutnumberSleep timeout
;(async function () {
    await sleep(2000);
})();

slice

source test1.0.0

Create slice of source array or array-like object.

NameTypeDesc
arrayarrayArray to slice
[start=0]numberStart position
[end=array.length]numberEnd position, not included
slice([1, 2, 3, 4], 1, 2); // -> [2]

slugify

source test1.7.0

Slugify a string.

NameTypeDesc
strstringString to slugify
[replacement]objectCustom replacement
returnstringSlugified string
slugify('I ♥ pony'); // -> 'I-love-pony'
slugify('I ♥ pony', {' ': '_'}); // -> 'I_love_pony'

snakeCase

source test1.0.0

Convert string to "snakeCase".

NameTypeDesc
strstringString to convert
returnstringSnake 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.

NameTypeDesc
objarray objectCollection to iterate over
predicatefunctionFunction to invoked per iteration
ctx*Predicate context
returnbooleanTrue 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.

NameTypeDesc
arrobject arrayCollection to iterate over
[iterator=identity]functionIterator to sort by
[ctx]*Iterator context
returnarrayNew sorted array
sortBy([1, 2, 3, 4, 5, 6], function (num) {
    return Math.sin(num);
}); // -> [5, 4, 6, 3, 1, 2]

spaceCase

source test1.0.0

Convert string to "spaceCase".

NameTypeDesc
strstringString to convert
returnstringSpace 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.

NameTypeDesc
strstringString to split
returnarrayResult 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.

NameTypeDesc
pathstringPath to split
returnobjectObject 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.

Stack trace API

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

startWith

source test1.0.0

Check if string starts with the given target string.

NameTypeDesc
strstringString to search
prefixstringString prefix
returnbooleanTrue if string starts with prefix
startWith('ab', 'a'); // -> true

strHash

source test1.0.0

String hash function using djb2.

NameTypeDesc
strstringString to hash
returnnumberHash result
strHash('test'); // -> 2090770981

strToBytes

source test1.1.0

Convert string into bytes.

NameTypeDesc
strstringString to convert
returnarrayBytes array
strToBytes('licia'); // -> [108, 105, 99, 105, 97]

stringify

source test1.0.0

JSON stringify with support for circular object, function etc.

Undefined is treated as null value.

NameTypeDesc
objobjectObject to stringify
spacesnumberIndent spaces
returnstringStringified 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.

NameTypeDesc
obj*Object to stringify
[options]objectStringify options
returnstringStringified object

Available options:

NameTypeDesc
unenumerable=falsebooleanInclude unenumerable keys
symbol=falsebooleanInclude symbol keys
accessGetter=falsebooleanAccess getter value
timeout=0numberTimeout of stringify
depth=0numberMax depth of recursion
[ignore]arrayValues to ignore

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

stringifyAll(function test() {}); // -> '{"value":"function test() {}","type":"Function",...}'

stripAnsi

source test1.0.0

Strip ansi codes from a string.

NameTypeDesc
strstringString to strip
returnstringResult string
stripAnsi('\u001b[4mcake\u001b[0m'); // -> 'cake'

stripCmt

source test1.0.0

Strip comments from source code.

NameTypeDesc
strstringSource code
returnstringCode 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.

NameTypeDesc
strstringString to strip
returnstringResult string
stripColor('\u001b[31mred\u001b[39m'); // -> 'red'

stripHtmlTag

source test1.0.0

Strip html tags from a string.

NameTypeDesc
strstringString to strip
returnstringResult string
stripHtmlTag('<p>Hello</p>'); // -> 'Hello'

stripIndent

source test1.5.4

Strip indentation from multi-line strings.

NameTypeDesc
strstringString to strip
returnstringResult 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'

sum

source test1.0.0

Compute sum of given numbers.

NameTypeDesc
...numnumberNumbers to calculate
returnnumberSum of numbers
sum(1, 2, 5); // -> 8

swap

source test1.0.0

Swap two items in an array.

NameTypeDesc
arrarrayArray to swap
anumberFirst index
bnumberSecond index
returnarrayArray given
const arr = [1, 2];
swap(arr, 0, 1); // -> [2, 1]

template

source test1.0.0

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

NameTypeDesc
strstringTemplate string
[util]objectUtility functions
returnfunctionCompiled 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.

NameTypeDesc
fnfunctionFunction to throttle
waitnumberNumber of milliseconds to delay
returnfunctionNew throttled function
const updatePos = throttle(function () {}, 100);
// $(window).scroll(updatePos);

through

source test1.0.0

Tiny wrapper of stream Transform.

NameTypeDesc
opts={}ObjectOptions to initialize stream
transformfunctionTransform implementation
[flush]functionFlush 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.

NameTypeDesc
dateDateDate to calculate
[now=new Date]DateCurrent date
returnstringFormatted time ago string
const now = new Date().getTime();
timeAgo(now - 1000 * 6); // -> right now
timeAgo(now + 1000 * 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.

NameTypeDesc
fnfunctionFunction to measure time
returnnumberExecution time, ms
timeTaken(function () {
    // Do something.
}); // -> Time taken to execute given function.

times

source test1.2.0

Invoke given function n times.

NameTypeDesc
nnumberTimes to invoke function
fnfunctionFunction invoked per iteration
[ctx]*Function context
returnarrayArray of results
times(3, String); // -> ['0', '1', '2']

toArr

source test1.0.0

Convert value to an array.

NameTypeDesc
val*Value to convert
returnarrayConverted 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.

NameTypeDesc
fnGeneratorFunctionGenerator function
returnfunctionResult 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.

NameTypeDesc
val*Value to convert
returnbooleanConverted 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.

NameTypeDesc
val*Value to convert
returnDateConverted Date
toDate('20180501');
toDate('2018-05-01');
toDate(1525107450849);

toEl

source test1.0.0

Convert html string to dom elements.

There should be only one root element.

NameTypeDesc
strstringHtml string
returnelementHtml element
toEl('<div>test</div>');

toInt

source test1.0.0

Convert value to an integer.

NameTypeDesc
val*Value to convert
returnnumberConverted integer
toInt(1.1); // -> 1
toInt(undefined); // -> 0

toNum

source test1.0.0

Convert value to a number.

NameTypeDesc
val*Value to process
returnnumberResult number
toNum('5'); // -> 5

toSrc

source test1.0.0

Convert function to its source code.

NameTypeDesc
fnfunctionFunction to convert
returnstringSource code
toSrc(Math.min); // -> 'function min() { [native code] }'
toSrc(function () {}) // -> 'function () { }'

toStr

source test1.0.0

Convert value to a string.

NameTypeDesc
val*Value to convert
returnstringResult string
toStr(null); // -> ''
toStr(1); // -> '1'
toStr(false); // -> 'false'
toStr([1, 2, 3]); // -> '1,2,3'

topoSort

source test1.0.0

Topological sorting algorithm.

NameTypeDesc
edgesarrayDependencies
returnarraySorted order
topoSort([[1, 2], [1, 3], [3, 2]]); // -> [1, 3, 2]

trigger

source test1.0.0

Trigger browser events.

NameTypeDesc
[el=document]elementElement to trigger
typestringEvent type
optionsobjectOptions
trigger(document.getElementById('#test'), 'mouseup');
trigger('keydown', {keyCode: 65});

trim

source test1.0.0

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

NameTypeDesc
strstringString to trim
charsstring arrayCharacters to trim
returnstringTrimmed string
trim(' abc  '); // -> 'abc'
trim('_abc_', '_'); // -> 'abc'
trim('_abc_', ['a', 'c', '_']); // -> 'b'

tryIt

source test1.0.0

Run function in a try catch.

NameTypeDesc
fnfunctionFunction to try catch
[cb]functionCallback
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.

NameTypeDesc
val*Value to get type
lowerCase=truebooleanLowerCase result
returnstringType 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.

ucs2

source test1.0.0

UCS-2 encoding and decoding.

encode

Create a string using an array of code point values.

NameTypeDesc
arrarrayArray of code points
returnstringEncoded string

decode

Create an array of code point values using a string.

NameTypeDesc
strstringInput string
returnarrayArray 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.

start

Start handling of errors.

stop

Stop handling.

addListener

Add listener for handling errors.

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

NameTypeDesc
strstringString to unescape
returnstringunescaped string
unescape('You &amp; Me'); // -> 'You & Me'

union

source test1.0.0

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

NameTypeDesc
...arrarrayArrays to inspect
returnarrayNew array of combined values
union([2, 1], [4, 2], [1, 2]); // -> [2, 1, 4]

uniqId

source test1.0.0

Generate a globally-unique id.

NameTypeDesc
[prefix]stringId prefix
returnstringGlobally-unique id
uniqId('eusita_'); // -> 'eustia_xxx'

unique

source test1.0.0

Create duplicate-free version of an array.

NameTypeDesc
arrarrayArray to inspect
[compare]functionFunction for comparing values
returnarrayNew 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.

NameTypeDesc
fnfunctionAsync function
typestringSource type, promise or callback
returnfunctionResult 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.

NameTypeDesc
arrarrayArray of grouped elements to process
returnarrayNew 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.

NameTypeDesc
strstringString to convert
returnstringUppercased string
upperCase('test'); // -> 'TEST'

upperFirst

source test1.0.0

Convert the first character of string to upper case.

NameTypeDesc
strstringString to convert
returnstringConverted string
upperFirst('red'); // -> Red

use

source test1.0.0

Use modules that is created by define.

NameTypeDesc
[requires]arrayDependencies
methodfunctionCodes 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.

encode

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

NameTypeDesc
strstringString to encode
returnstringEncoded string

decode

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

NameTypeDesc
strstringString to decode
safe=falsebooleanSuppress error if true
returnstringDecoded 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.

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.

NameTypeDesc
objobjectObject to query
returnarrayArray of property values
values({one: 1, two: 2}); // -> [1, 2]

viewportScale

source test1.0.0

Get viewport scale.

viewportScale(); // -> 3

vlq

source test1.4.0

Variable-length quantity encoding and decoding.

encode

Encode numbers into vlq string.

NameTypeDesc
numbernumber arrayNumber to encode
returnstringEncoded string

decode

Decode vlq string into numbers.

NameTypeDesc
stringstringString to decode
returnarrayDecoded 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.

NameTypeDesc
conditionfunctionCondition function
[timeout=0]numberTimeout
[interval=250]numberWait 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.

NameTypeDesc
tasksarrayArray of functions
[cb]functionCallback once completed
waterfall([
    function (cb) {
        cb(null, 'one');
    },
    function (arg1, cb) {
        // arg1 -> 'one'
        cb(null, 'done');
    }
], function (err, result) {
    // result -> 'done'
});

workerize

source test demo1.0.0

Move a stand-alone function to a worker thread.

NameTypeDesc
fnfunctionFunction to turn
returnfunctionWorkerized 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.

NameTypeDesc
fnfunctionFunction to wrap
wrapperfunctionWrapper function
returnfunctionNew 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.

wx.getStorage('test').then(res => {
    console.log(res.data);
});

zip

source test1.0.0

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

NameTypeDesc
...arrarrayArrays to process
returnarrayNew array of grouped elements
zip(['a', 'b'], [1, 2], [true, false]); // -> [['a', 1, true], ['b', 2, false]]