English 中文

All source code is hosted on GitHub.

Feel free to report issues and make pull requests:)

Use as an npm package:

npm i licia --save
var uuid = require('licia/uuid');

console.log(uuid()); // -> 0e3b84af-f911-4a55-b78a-cedf6f0bd815

$

source test

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

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

$attr

source test

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 test

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
namesstringClass 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 test

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 test

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

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

$event

source test

bind events to certain dom elements.

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

$insert

source test

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 test

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 test

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 test

Remove the set of matched elements from the DOM.

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

$safeEls

source test

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

NameTypeDesc
valueelement array stringValue to convert
returnarrayArray of elements
$safeEls('.test'); // -> Array of elements with test class

$show

source test

Show elements.

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

Blob

source test

Use Blob when available, otherwise BlobBuilder.

constructor

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

Class

source test demo

Create JavaScript class.

NameTypeDesc
methodsobjectPublic methods
[statics]objectStatic methods
returnfunctionFunction used to create instances
var People = Class({
    initialize: function People(name, age) {
        this.name = name;
        this.age = age;
    },
    introduce: function () {
        return 'I am ' + this.name + ', ' + this.age + ' years old.';
    }
});

var 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;
    }
});

var 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 test

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'}
var color = new Color('#abc');
color.toRgb(); // -> 'rgb(170, 187, 204)'
color.toHsl(); // -> 'hsl(210, 25%, 73%)'

Dispatcher

source test

Flux dispatcher.

Related docs

var dispatcher = new Dispatcher();

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

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

Emitter

source test

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
var event = new Emitter();
event.on('test', function () { console.log('test') });
event.emit('test'); // Logs out 'test'.
Emitter.mixin({});

Enum

source test

Enum type implementation.

constructor

NameTypeDesc
arrarrayArray of strings
NameTypeDesc
objobjectPairs of key and value
var importance = new Enum([
    'NONE', 'TRIVIAL', 'REGULAR', 'IMPORTANT', 'CRITICAL'
]);

if (val === importance.CRITICAL) {
    // Do something.
}

JsonTransformer

source test

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
var 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 test

Doubly-linked list implementation.

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.

forEach

Iterate over the list.

toArr

Convert the list to a JavaScript array.

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

LocalStore

source test

LocalStorage wrapper.

Extend from Store.

constructor

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

Logger

source test demo

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.

var 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.
});

MutationObserver

source test

Safe MutationObserver, does nothing if MutationObserver is not supported.

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

Promise

source test demo

Lightweight Promise implementation.

Promises spec

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

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

PseudoMap

source test

Like es6 Map, without iterators.

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

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

Queue

source test

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
iterateefunctionFunction invoked iteration
[ctx]*Function context

toArr

Convert queue to a JavaScript array.

var 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

ReduceStore

source test

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 unscribe

dispatch

Dispatch an action.

NameTypeDesc
actionobjectObject representing changes
returnobjectSame action object

getState

Get the current state.

var 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 test

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
var $test = new Select('#test');
$test.find('.test').each(function (idx, element) {
    // Manipulate dom nodes
});

SessionStore

source test

SessionStorage wrapper.

Extend from Store.

constructor

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

Stack

source test

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
iterateefunctionFunction invoked iteration
[ctx]*Function context

toArr

Convert the stack to a JavaScript array.

var stack = new Stack();

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

State

source test

Simple state machine.

Extend from Emitter.

constructor

NameTypeDesc
initialstringInitial state
eventsstringEvents to change state

is

Check current state.

NameTypeDesc
valuestringState to check
returnbooleanTrue if current state equals given value
var 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 test

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
var 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 demo

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
var pos = {x: 0, y: 0};

var 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 test

Simple url manipulator.

constructor

NameTypeDesc
url=locationstringUrl string

setQuery

Set query value.

NameTypeDesc
namestringQuery name
valuestringQuery value
returnUrlthis
NameTypeDesc
namesobjectquery 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 (#)
var url = new Url('http://example.com:8080?eruda=true');
console.log(url.port); // -> '8080'
url.query.foo = 'bar';
url.rmQuery('eruda');
utl.toString(); // -> 'http://example.com:8080/?foo=bar'

Validator

source test

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';
});
var 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 test

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 test

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
var fn = after(5, function() {
    // -> Only invoke after fn is called 5 times.
});

ajax

source test

Perform an asynchronous HTTP request.

NameTypeDesc
optionsobjectAjax options

Available options:

NameTypeDesc
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: function () {},
    success: function (data) {
        // ...
    },
    dataType: 'json'
});

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

allKeys

source test

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

NameTypeDesc
objobjectObject to query
returnarrayArray of all property names

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

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

arrToMap

source test

Make an object map using array of strings.

NameTypeDesc
arrarrayArray of strings
val=true*Key value
returnobjectObject map
var needPx = arrToMap([
    'column-count', 'columns', 'font-weight', 'line-weight', 'opacity', 'z-index', 'zoom'
]);

if (needPx[key]) val += 'px';

atob

source test

Use Buffer to emulate atob when running in node.

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

average

source test

Get average value of given numbers.

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

base64

source test

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 test

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.

$(element).on('click', before(5, function() {}));
// -> allow function to be call 4 times at last.

bind

source test

Create a function bound to a given object.

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

Use Buffer to emulate btoa when running in node.

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

bubbleSort

source test

Bubble sort implementation.

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

bytesToStr

source test

Convert bytes to string.

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

callbackify

source test

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) {
        // ...
    });
}

var cbFn = callbackify(fn);

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

camelCase

source test

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 test

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

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

castPath

source test

Cast value into a property path array.

NameTypeDesc
str*Value 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 test

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 test

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 test

Split array into groups the length of given size.

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

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 test

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 test

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 test

Recursively clone value.

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

cmpVersion

source test

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 test

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 test

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 test

Compose a list of functions.

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

NameTypeDesc
...fnfunctionFunctions to compose
returnfunctionComposed function
var welcome = compose(function (name) {
    return 'hi: ' + name;
}, function (name) {
    return name.toUpperCase() + '!';
});

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

compressImg

source test demo

Compress image using canvas.

NameTypeDesc
fileFile BlobImage file
optsobjectOptions
cbfunctionCallback

Available options:

NameTypeDesc
maxWidthnumberMax width
maxHeightnumberMax height
widthnumberOutput image width
heightnumberOutput image height
mineTypestringMine 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.

compressImg(file, {
    maxWidth: 200
}, function (err, file) {
    // ...
});

concat

source test

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 test

Check if the value is present in the list.

NameTypeDesc
arrayarray objectTarget list
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

convertBase

source test

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'

source test

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 demo

Copy text to clipboard using document.execCommand.

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

createAssigner

source test

Used to create extend, extendOwn and defaults.

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

createUrl

source test

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 test

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 test

Function currying.

NameTypeDesc
fnfunctionFunction to curry
returnfunctionNew curried function
var add = curry(function (a, b) { return a + b });
var add1 = add(1);
add1(2); // -> 3

dateFormat

source test

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 test

Return a new debounced version of the passed function.

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

debug

source test demo

A tiny JavaScript debugging utility.

NameTypeDesc
namestringNamespace
returnfunctionFunction to print decorated log
var d = debug('test');
d('doing lots of uninteresting work');
d.enabled = false;

decodeUriComponent

source test

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 test

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 test

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 test

Shortcut for Object.defineProperty(defineProperties).

NameTypeDesc
objobjectObject to define
propstringProperty path
descriptorobjectProperty descriptor
returnobjectObject itself
NameTypeDesc
objobjectObject to define
propobjectProperty descriptors
returnobjectObject itself
var obj = {b: {c: 3}, d: 4, e: 5};
defineProp(obj, 'a', {
    get: function () {
        return this.e * 2;
    }
});
console.log(obj.a); // -> 10
defineProp(obj, 'b.c', {
    set: (function (val) {
        // this is pointed to obj.b
        this.e = val;
    }).bind(obj)
});
obj.b.c = 2;
console.log(obj.a); // -> 4;

obj = {a: 1, b: 2, c: 3};
defineProp(obj, {
    a: {
        get: function () {
            return this.c;
        }
    },
    b: {
        set: function (val) {
            this.c = val / 2;
        }
    }
});
console.log(obj.a); // -> 3
obj.b = 4;
console.log(obj.a); // -> 2

delay

source test

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 test

Event delegation.

add

Add event delegation.

NameTypeDesc
elelementParent element
typestringEvent type
selectorstringMatch selector
cbfunctionEvent callback

remove

Remove event delegation.

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

detectBrowser

source test

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)

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

detectMocha

source test

Detect if mocha is running.

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

detectOs

source test

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 test

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 test

Convert string to "dotCase".

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

download

source test demo

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 benchmark

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 test

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

endWith

source test

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 test

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

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

escapeJsStr

source test

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 test

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

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

evalCss

source test

Load css into page.

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

evalJs

source test benchmark

Execute js in given context.

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

every

source test

Check if predicate return truthy for all elements.

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

extend

source test

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

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

extendDeep

source test

Recursive object extending.

NameTypeDesc
objobjectDestination object
...srcobjectSources 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 test

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

NameTypeDesc
objobjectDestination object
*srcobjectSources objects
returnobjectDestination object
extendOwn({name: 'RedHood'}, {age: 24}); // -> {name: 'RedHood', age: 24}

extractBlockCmts

source test

Extract block comments from source code.

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

extractUrls

source test

Extract urls from plain text.

NameTypeDesc
strstringText to extract
returnarrayUrl list
var str = '[Official site: http://eustia.liriliri.io](http://eustia.liriliri.io)';
extractUrl(str); // -> ['http://eustia.liriliri.io']

fetch

source test

Turn XMLHttpRequest into promise like.

Note: This is not a complete fetch pollyfill.

NameTypeDesc
urlstringRequest url
optionsobjectRequest 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 test

Calculate fibonacci number.

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

fileSize

source test

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'

fill

source test

Fill elements of array with value.

NameTypeDesc
arrarrayArray to fill
val*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 test

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 test

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

NameTypeDesc
objarray objectCollection to iterate over
predicatefunctionFunction invoked per iteration
[ctx]*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 test

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 test

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 test

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 test

Recursively flatten an array.

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

fnParams

source test

Get a function parameter's names.

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

format

source test

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 test

Convert number to fraction.

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

freeze

source test

Shortcut for Object.freeze.

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

NameTypeDesc
objobjectObject to freeze
returnobjectObject passed in
var a = {b: 1};
freeze(a);
a.b = 2;
console.log(a); // -> {b: 1}

freezeDeep

source test

Recursively use Object.freeze.

NameTypeDesc
objobjectObject to freeze
returnobjectObject passed in
var a = {b: {c: 1}};
freezeDeep(a);
a.b.c = 2;
console.log(a); // -> {b: {c: 1}}

fs

source test

Promised version of node.js fs module.

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

gcd

source test

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 test

Get an available TCP port.

NameTypeDesc
[port]number arrayPreferred ports
returnpromiseAvailable port

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

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

getUrlParam

source test

Get url param.

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

has

source test

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

hotkey

source test demo

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 test

Convert hsl to rgb.

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

identity

source test

Return the first argument given.

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

idxOf

source test

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 test

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 test

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);
var s = new Student('RedHood');
s.getName(); // -> 'RedHood'

insertionSort

source test

Insertion sort implementation.

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

intersect

source test

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 test

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 test

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 test

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 test

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 test

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 test

Check if value is an ArrayBuffer.

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

isArrLike

source test

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 test

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 test

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 test

Check if running in a browser.

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

isBuffer

source test

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 test

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 test

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 test

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 test

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 test

Loosely validate an email address.

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

isEmpty

source test

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 test

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 test

Check if value is an error.

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

isEven

source test

Check if number is even.

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

isFile

source test

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 test

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 test

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

isGeneratorFn

source test

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 test

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

isJson

source test

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 test

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 test

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 test

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 test

Check if running in wechat mini program.

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

isMobile

source test

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 test

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 test

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 test

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 test

Check if running in node.

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

isNull

source test

Check if value is an Null.

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

isNum

source test

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 test

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(0144); // -> true
isNumeric(0xFF); // -> true
isNumeric(''); // -> false
isNumeric('1.1.1'); // -> false
isNumeric(NaN); // -> false

isObj

source test

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 test

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 test

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

isPrime

source test

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 test

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 test

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 test

Check if value is a regular expression.

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

isRelative

source test

Check if path appears to be relative.

NameTypeDesc
pathstringPath to check
returnbooleanTrue if path appears to be relative
isRelative('README.md'); // -> true

isRetina

source test

Determine if running on a high DPR device or not.

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

isSet

source test

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 test

Check if an array is sorted.

NameTypeDesc
arrarrayArray to check
[cmp]functionComparator
isSorted([1, 2, 3]); // -> true
isSorted([3, 2, 1]); // -> false

isStr

source test

Check if value is a string primitive.

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

isStream

source test

Check if value is a Node.js stream.

NameTypeDesc
val*Value to check
returnbooleanTrue if value is a Node.js stream
var stream = require('stream');

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

isTypedArr

source test

Check if value is a typed array.

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

isUndef

source test

Check if value is undefined.

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

isUrl

source test

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 test

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 test

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 test

Check if platform is windows.

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

jsonp

source test

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 test

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 test

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 test

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

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

last

source test

Get the last element of array.

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

lazyRequire

source test

Require modules lazily.

var r = lazyRequire(require);

var _ = r('underscore');

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

linkify

source test

Hyperlink urls in a string.

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

Inject link tag into page with given href value.

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

loadImg

source test

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 test

Inject script tag into page with given src value.

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

longest

source test

Get the longest item in an array.

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

lowerCase

source test

Convert string to lower case.

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

lpad

source test

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

NameTypeDesc
strstringString to pad
lennumberPadding length
[chars]stringString used as padding
returnstringResulted string
lpad('a', 5); // -> '    a'
lpad('a', 5, '-'); // -> '----a'
lpad('abc', 3, '-'); // -> 'abc'
lpad('abc', 5, 'ab'); // -> 'ababc'

ltrim

source test

Remove chars or white-spaces from beginning of string.

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

map

source test

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

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

mapObj

source test

Map for objects.

NameTypeDesc
objobjectObject to iterate over
iterateefunctionFunction invoked per iteration
[ctx]*Function context
returnobjectNew mapped object
mapObj({a: 1, b: 2}, function (val, key) { return val + 1 }); // -> {a: 2, b: 3}

matcher

source test

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

NameTypeDesc
attrsobjectObject of property values to match
returnfunctionNew predicate function
var 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 test

Get maximum value of given numbers.

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

md5

source test

MD5 implementation.

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

memStorage

source test

Memory-backed implementation of the Web Storage API.

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

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

memoize

source test

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
var fibonacci = memoize(function(n) {
    return n < 2 ? n : fibonacci(n - 1) + fibonacci(n - 2);
});

mergeSort

source test

Merge sort implementation.

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

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

meta

source test

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 test

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', ...]

min

source test

Get minimum value of given numbers.

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

mkdir

source test

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 test

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 test

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 test

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 test

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 test

A no-operation function.

noop(); // Does nothing

normalizeHeader

source test

Normalize http header name.

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

normalizePath

source test

Normalize file path slashes.

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

now

source test

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

now(); // -> 1468826678701

objToStr

source test

Alias of Object.prototype.toString.

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

omit

source test

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 test

Create a function that invokes once.

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

open

source test

Open stuff like url, files.

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

optimizeCb

source test

Used for function context binding.

orientation

source test demo

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 test

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

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

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 test

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 test

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}

partial

source test

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
var sub5 = partial(function (a, b) { return b - a }, 5);
sub(20); // -> 15

pascalCase

source test

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 test

High resolution time up to microsecond precision.

var start = perfNow();

// Do something.

console.log(perfNow() - start);

pick

source test

Return a filtered copy of an object.

NameTypeDesc
objobjectSource 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 test

Extract a list of property values.

NameTypeDesc
objobject arrayCollection to iterate over
keystring arrayProperty path
returnarrayNew array of specified property
var stooges = [
    {name: 'moe', age: 40},
    {name: 'larry', age: 50},
    {name: 'curly', age: 60}
];
pluck(stooges, 'name'); // -> ['moe', 'larry', 'curly']

precision

source test

Find decimal precision of a given number.

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

prefix

source test

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 test

Convert callback based functions into Promises.

NameTypeDesc
fnfunctionCallback based function
multiArgs=falsebooleanIf callback has multiple success value
returnbooleanResult function

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

var fs = require('fs');

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

property

source test

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
var obj = {a: {b: 1}};
property('a')(obj); // -> {b: 1}
property(['a', 'b'])(obj); // -> 1

query

source test

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 benchmark

Quick sort implementation.

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

raf

source test

Shortcut for requestAnimationFrame.

Use setTimeout if native requestAnimationFrame is not supported.

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

random

source test

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 test

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]

randomItem

source test

Get a random item from an array.

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

range

source test

Create flexibly-numbered lists of integers.

NameTypeDesc
[start]numberStart of the range
endnumberEnd of the range
step=1numberValue to increment or decrement by
range(5); // -> [0, 1, 2, 3, 4]
range(0, 5, 2) // -> [0, 2, 4]

rc4

source test

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 test

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 benchmark

Turn a list of values into a single value.

NameTypeDesc
objobject arrayCollection to iterate over
iteratee=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 test

Right-associative version of reduce.

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

reject

source test

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 test

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
objarrayCollection to iterate over
predicatefunctionFunction invoked per iteration
[ctx]*Predicate context
returnarrayArray of all values that are removed
var arr = [1, 2, 3, 4, 5];
var evens = remove(arr, function (val) { return val % 2 === 0 });
console.log(arr); // -> [1, 3, 5]
console.log(evens); // -> [2, 4]

repeat

source test

Repeat string n-times.

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

restArgs

source test

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
var paramArr = restArgs(function (rest) { return rest });
paramArr(1, 2, 3, 4); // -> [1, 2, 3, 4]

rgbToHsl

source test

Convert rgb to hsl.

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

rmCookie

source test

Loop through all possible path and domain to remove cookie.

NameTypeDesc
keystringCookie key
rmCookie('test');

rmdir

source test

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 test

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

rpad

source test

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

NameTypeDesc
strstringString to pad
lennumberPadding length
charsstringString used as padding
returnstringResulted string
rpad('a', 5); // -> 'a    '
rpad('a', 5, '-'); // -> 'a----'
rpad('abc', 3, '-'); // -> 'abc'
rpad('abc', 5, 'ab'); // -> 'abcab'

rtrim

source test

Remove chars or white-spaces from end of string.

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

safeCb

source test

Create callback based on input value.

safeDel

source test

Delete object property.

NameTypeDesc
objobjectObject to query
patharray stringPath of property to delete
return*Deleted value or undefined
var obj = {a: {aa: {aaa: 1}}};
safeDel(obj, 'a.aa.aaa'); // -> 1
safeDel(obj, ['a', 'aa']); // -> {}
safeDel(obj, 'a.b'); // -> undefined

safeGet

source test

Get object property, don't throw undefined error.

NameTypeDesc
objobjectObject to query
patharray stringPath of property to get
return*Target value or undefined
var obj = {a: {aa: {aaa: 1}}};
safeGet(obj, 'a.aa.aaa'); // -> 1
safeGet(obj, ['a', 'aa']); // -> {aaa: 1}
safeGet(obj, 'a.b'); // -> undefined

safeSet

source test

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
var 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 test

Use storage safely in safari private browsing and older browsers.

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

sample

source test

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 demo

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 test

Selection sort implementation.

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

shuffle

source test

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 test

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

slice

source test

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]

snakeCase

source test

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 test

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 test

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

NameTypeDesc
arrobject arrayCollection to iterate over
[iteratee=identity]functionIteratee to sort by
[ctx]*Iteratee 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 test

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 test

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 test

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'}

startWith

source test

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 test

String hash function using djb2.

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

strToBytes

source test

Convert string into bytes.

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

stringify

source test

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 () {}]"}'
var obj = {a: 1};
obj.b = obj;
stringify(obj); // -> '{"a":1,"b":"[Circular ~]"}'

stripAnsi

source test

Strip ansi codes from a string.

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

stripCmt

source test

Strip comments from source code.

NameTypeDesc
strstringSource code
returnstringCode without comments
stripCmts('// comment \n var a = 5; /* comment2\n * comment3\n *\/'); // -> ' var a = 5; '

stripColor

source test

Strip ansi color codes from a string.

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

stripHtmlTag

source test

Strip html tags from a string.

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

sum

source test

Compute sum of given numbers.

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

swap

source test

Swap two items in an array.

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

template

source test

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

NameTypeDesc
strstringTemplate string
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!'

throttle

source test

Return a new throttled version of the passed function.

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

through

source test

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.

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 test

Format datetime with * time ago statement.

NameTypeDesc
dateDateDate to calculate
[now=new Date]DateCurrent date
returnstringFormatted time ago string
var 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 test

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 test

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', '3']

toArr

source test

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); // -> []

toBool

source test

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 test

Convert value to a Date.

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

toEl

source test

Convert html string to dom elements.

There should be only one root element.

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

toInt

source test

Convert value to an integer.

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

toNum

source test

Convert value to a number.

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

toSrc

source test

Convert function to its source code.

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

toStr

source test

Convert value to a string.

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

topoSort

source test

Topological sorting algorithm.

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

trigger

source test

Trigger browser events.

NameTypeDesc
[el=document]elementElement to trigger
typestringEvent type
optsobjectOptions
trigger(el, 'mouseup');
trigger('keydown', {keyCode: 65});

trim

source test

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 test

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 test

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

NameTypeDesc
val*Value to get type
returnstringType of object, lowercased
type(5); // -> 'number'
type({}); // -> 'object'
type(function () {}); // -> 'function'
type([]); // -> 'array'

ucs2

source test

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 demo

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 test

Convert HTML entities back, the inverse of escape.

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

union

source test

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 test

Generate a globally-unique id.

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

unique

source test

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]

unzip

source test

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 test

Convert string to upper case.

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

upperFirst

source test

Convert the first character of string to upper case.

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

use

source test

Use modules that is created by define.

NameTypeDesc
[requires]arrayDependencies
methodfunctionCodes to be executed
define('A', function () {
    return 'A';
});
use(['A'], function (A) {
    console.log(A + 'B'); // -> 'AB'
});

utf8

source test

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 benchmark

RFC4122 version 4 compliant uuid generator.

Check RFC4122 4.4 for reference.

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

values

source test

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 test

Get viewport scale.

viewportScale(); // -> 3

waterfall

source test

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 demo

Move a stand-alone function to a worker thread.

NameTypeDesc
fnfunctionFunction to turn
returnfunctionWorkerized Function
var worker = workerize(function (a, b) {
    return a + b;
});
worker(1, 2).then(function (value) {
    console.log(value); // -> 3
});

wrap

source test

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

NameTypeDesc
fn*Function to wrap
wrapperfunctionWrapper function
returnfunctionNew function
var p = wrap(escape, function(fn, text) {
    return '<p>' + fn(text) + '</p>';
});
p('You & Me'); // -> '<p>You &amp; Me</p>'

zip

source test

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