Licia:最全最实用的 JavaScript 工具库

前言

在业务开发过程中,我们经常会重复使用日期格式化cookie 操作模板浏览器判断类型判断等功能。为了避免不同项目之间进行复制粘贴,可以将这些常用的函数封装到一起并发布 npm 包。在将近三年的前端开发工作中,笔者将自己平时用到的工具库统统封装到了一个项目中 Licia。目前所包含模块已达三百个,基本可以满足前端的日常工发需求。如果你对该项目感兴趣,欢迎试用并帮忙持续改进:)

使用方法

一、安装 npm 包

首先安装 npm 包到本地。

npm i licia --save
复制代码

安装完之后,你就可以直接在项目中引用模块了,就像使用 lodash 一样。

var uuid = require('licia/uuid');

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

二、使用打包工具

该项目自带打包工具 eustia,可以通过配置文件或命令行扫描源码自动生成项目专用的工具库。

npm i eustia -g
复制代码

假设你想html文件中使用trim方法,先直接在代码中使用:

<html>
<head>
    <meta charset="utf-8"/>
    <title>Eustia</title>
    <script src="util.js"></script>
</head>
<body>
    <script>
    var projectName = _.trim(' Eustia ');
    // Some code...
    </script>
</body>
</html>
复制代码

然后跑下命令:

eustia build
复制代码

该工具会扫描你的html代码并生成一个util.js(默认文件名)文件,大功告成!

PS: 之前做的手机调试工具 eruda 源码里的 util.js 就是使用该工具生成的:)

三、使用在线工具生成 util 库

你可以直接访问 eustia.liriliri.io/builder.htm… 在输入框输入需要的工具函数(以空格分隔),然后点击下载 util.js 文件并将该文件放入项目中去即可。

比如在小程序中你需要使用时间格式化,直接输入 dateFormat 后将生成的 util.js 放入小程序源码中,之后再在代码里引用:

import { dateFormat } from './util.js';

dateFormat(1525764204163, 'yyyy-mm-dd HH:MM:ss'); // -> '2018-05-08 15:23:24'
复制代码

支持模块汇总

$

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

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

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

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

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

$data('#test', 'attr1', 'eustia');
复制代码

$event

bind events to certain dom elements.

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

$insert

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

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

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

Remove the set of matched elements from the DOM.

NameTypeDesc
elementstring array elementElements to delete
$remove('#test');
复制代码

$safeEls

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

Show elements.

NameTypeDesc
elementstring array elementElements to show
$show('#test');
复制代码

Blob

Use Blob when available, otherwise BlobBuilder.

constructor

NameTypeDesc
partsarrayBlob parts
[opts]objectOptions
var blob = new Blob([]);
复制代码

Class

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

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

Flux dispatcher.

Related docs.

var dispatcher = new Dispatcher();

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

dispatcher.dispatch({
    actionType: 'action'
});
复制代码

Emitter

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

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

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

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

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

LocalStorage wrapper.

Extend from Store.

constructor

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

Logger

Simple logger with level filter.

constructor

NameTypeDesc
namestringLogger name
[level=DEBUG]numberLogger level

setLevel

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

Safe MutationObserver, does nothing if MutationObserver is not supported.

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

Promise

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...
});
复制代码

Queue

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

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

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

SessionStorage wrapper.

Extend from Store.

constructor

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

Stack

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

var stack = new Stack();

stack.push(2); // -> 1
stack.push(3); // -> 2
stack.pop(); // -> 3
复制代码

State

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

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

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

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

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

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

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

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

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

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

Use Buffer to emulate atob when running in node.

atob('SGVsbG8gV29ybGQ='); // -> 'Hello World'
复制代码

average

Get average value of given numbers.

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

base64

Basic base64 encoding and decoding.

encode

Turn a byte array into a base64 string.

NameTypeDesc
arrarrayByte array
returnstringBase64 string
base64.encode([168, 174, 155, 255]); // -> 'qK6b/w=='
复制代码

decode

Turn a base64 string into a byte array.

NameTypeDesc
strstringBase64 string
returnarrayByte array
base64.decode('qK6b/w=='); // -> [168, 174, 155, 255]
复制代码

before

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

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

Use Buffer to emulate btoa when running in node.

btoa('Hello World'); // -> 'SGVsbG8gV29ybGQ='
复制代码

bubbleSort

Bubble sort implementation.

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

callbackify

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

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

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

NameTypeDesc
strstringString to capitalize
returnstringCapitalized string
capitalize('rED'); // -> Red
复制代码

castPath

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

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

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

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

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

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

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

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

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
复制代码

compact

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

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

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

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

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

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'
复制代码

cookie

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

Copy text to clipboard using document.execCommand.

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

createAssigner

Used to create extend, extendOwn and defaults.

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

createUrl

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

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

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

Simple but extremely useful date format function.

NameTypeDesc
[date=new Date]DateDate object to format
maskstringFormat mask
[utc=false]booleanUTC or not
[gmt=false]booleanGMT 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

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

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

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

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

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

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

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

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

Detect browser info using ua.

NameTypeDesc
[ua=navigator.userAgent]stringBrowser 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...
}
复制代码

detectOs

Detect operating system using ua.

NameTypeDesc
[ua=navigator.userAgent]stringBrowser userAgent
returnstringOperating system name

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

if (detectOs() === 'ios')
{
    // Do something about ios...
}
复制代码

difference

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

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

dotCase

Convert string to "dotCase".

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

download

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

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

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

easing

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

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

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

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

escapeJsStr

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

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

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

evalCss

Load css into page.

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

evalJs

Execute js in given context.

NameTypeDesc
jsstringJavaScript code
[ctx=global]objectContext
evalJs('5+2'); // -> 7
evalJs('this.a', {a: 2}); // -> 2
复制代码

every

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

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

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

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

Extract block comments from source code.

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

extractUrls

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

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

Calculate fibonacci number.

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

fileSize

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

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

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

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

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

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

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

Recursively flatten an array.

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

fnParams

Get a function parameter's names.

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

format

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

Convert number to fraction.

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

freeze

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

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}}
复制代码

gcd

Compute the greatest common divisor using Euclid's algorithm.

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

getUrlParam

Get url param.

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

has

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

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

Convert hsl to rgb.

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

identity

Return the first argument given.

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

idxOf

Get the index at which the first occurrence of value.

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

indent

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

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

Insertion sort implementation.

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

intersect

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

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

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 unless multiValue is true.

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

isAbsoluteUrl

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

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

Check if value is an Array object.

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

isArrBuffer

Check if value is an ArrayBuffer.

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

isArrLike

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

Check if value is a Blob.

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

isBool

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

Check if running in a browser.

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

isBuffer

Check if value is a buffer.

NameTypeDesc
val*The value to check
returnbooleanTrue if value is a buffer
isBuffer(new Buffer(4)); // -> true
复制代码

isClose

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

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

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

Check if value is a DOM element.

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

isEmail

Loosely validate an email address.

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

isEmpty

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

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

Check if value is an error.

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

isEven

Check if number is even.

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

isFile

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

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

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

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

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

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

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
复制代码

isMatch

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

Check if running in wechat mini program.

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

isMobile

Check whether client is using a mobile browser using ua.

NameTypeDesc
[ua=navigator.userAgent]stringUser agent
returnbooleanTrue if ua belongs to mobile browsers
isMobile(navigator.userAgent);
复制代码

isNaN

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

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

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

Check if running in node.

console.log(isNode); // -> true if running in node
复制代码

isNull

Check if value is an Null.

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

isNum

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

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

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

Check if number is odd.

NameTypeDesc
numnumberNumber to check
returnbooleanTrue if number is odd
isOdd(0); // -> false
isOdd(1); // -> true
isOdd(2); // -> false
复制代码

isPlainObj

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
复制代码

isPrimitive

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

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

Check if value is a regular expression.

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

isRelative

Check if path appears to be relative.

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

isRetina

Determine if running on a high DPR device or not.

console.log(isRetina); // -> true if high DPR
复制代码

isStr

Check if value is a string primitive.

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

isStream

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

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

Check if value is undefined.

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

isUrl

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
复制代码

isWindows

Check if platform is windows.

console.log(isWindows); // -> true if running on windows
复制代码

jsonp

A simple jsonp implementation.

NameTypeDesc
optsobjectJsonp Options

Available options:

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

kebabCase

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

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

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

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

last

Get the last element of array.

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

lazyRequire

Require modules lazily.

var r = lazyRequire(require);

var _ = r('underscore');

// underscore is required only when _ is called.
_().isNumber(5);
复制代码

linkify

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

Inject link tag into page with given href value.

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

loadImg

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

Inject script tag into page with given src value.

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

longest

Get the longest item in an array.

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

lowerCase

Convert string to lower case.

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

lpad

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

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

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

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

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

Get maximum value of given numbers.

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

memStorage

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

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);
});
复制代码

meta

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

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

Get minimum value of given numbers.

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

mkdir

Recursively create directories.

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

moment

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

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

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

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

A no-operation function.

noop(); // Does nothing
复制代码

normalizePath

Normalize file path slashes.

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

now

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

now(); // -> 1468826678701
复制代码

objToStr

Alias of Object.prototype.toString.

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

omit

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 

Create a function that invokes once.

|Name  |Type    |Desc                   |
|------|--------|-----------------------|
|fn    |function|Function to restrict   |
|return|function|New restricted function|

```javascript
function init() {};
var initOnce = once(init);
initOnce();
initOnce(); // -> init is invoked once
复制代码

optimizeCb

Used for function context binding.

orientation

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

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

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

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

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

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

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

High resolution time up to microsecond precision.

var start = perfNow();

// Do something.

console.log(perfNow() - start);
复制代码

pick

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

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

Find decimal precision of a given number.

NameTypeDesc
numnumberNumber to check
returnnumberPrecision
precision(1.234); // -> 3;
复制代码

prefix

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

Convert callback based functions into Promises.

NameTypeDesc
fnfunctionCallback based function
[multiArgs=false]booleanIf 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

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

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']}
复制代码

raf

Shortcut for requestAnimationFrame.

Use setTimeout if native requestAnimationFrame is not supported.

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

random

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

NameTypeDesc
minnumberMinimum possible value
maxnumberMaximum possible value
[floating=false]booleanFloat 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

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]
复制代码

range

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]
复制代码

ready

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

NameTypeDesc
fnfunctionCallback function
ready(function ()
{
    // It's safe to manipulate dom here.
});
复制代码

reduce

Turn a list of values into a single value.

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

reduceRight

Right-associative version of reduce.

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

reject

Opposite of filter.

NameTypeDesc
objarrayCollection to iterate over
predicatefunctionFunction invoked per iteration
[ctx]*Predicate context
returnarrayArray of all values that pass predicate
reject([1, 2, 3, 4, 5], function (val)
{
    return val % 2 === 0;
}); // -> [1, 3, 5]
复制代码

remove

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

Repeat string n-times.

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

restArgs

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

NameTypeDesc
functionfunctionFunction that needs rest parameters
startIndexnumberThe 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

Convert rgb to hsl.

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

rmCookie

Loop through all possible path and domain to remove cookie.

NameTypeDesc
keystringCookie key
rmCookie('test');
复制代码

rmdir

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

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

rpad

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

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

Create callback based on input value.

safeDel

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

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

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

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

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

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

Selection sort implementation.

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

shuffle

Randomize the order of the elements in a given array.

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

size

Get size of object, length of array like object or the number of keys.

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

slice

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

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

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
复制代码

spaceCase

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

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

Split path into device, 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

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

String hash function using djb2.

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

stringify

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

Strip ansi codes from a string.

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

stripCmt

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

Strip ansi color codes from a string.

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

stripHtmlTag

Strip html tags from a string.

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

sum

Compute sum of given numbers.

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

template

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

NameTypeString
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

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

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

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

Get execution time of a function.

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

toArr

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

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

Convert value to a Date.

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

toEl

Convert html string to dom elements.

There should be only one root element.

NameTypeDesc
strstringHtml string
returnelementHtml element
toEl('<div>test</div>');
复制代码

toInt

Convert value to an integer.

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

toNum

Convert value to a number.

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

toSrc

Convert function to its source code.

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

toStr

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

Topological sorting algorithm.

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

trigger

Trigger browser events.

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

trim

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

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

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

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
复制代码

unescape

Convert HTML entities back, the inverse of escape.

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

union

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

Generate a globally-unique id.

NameTypeDesc
prefixstringId prefix
returnstringGlobally-unique id
uniqId('eusita_'); // -> 'eustia_xxx'
复制代码

unique

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

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

Convert string to upper case.

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

upperFirst

Convert the first character of string to upper case.

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

use

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

UTF-8 encoding and decoding.

encode

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

NameTypeDesc
strstringString to encode
returnstringEncoded string

decode

NameTypeDesc
strstringString to decode
[safe=false]booleanSuppress error if true
returnstringDecoded string

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

utf8.encode('\uD800\uDC00'); // ->  '\xF0\x90\x80\x80'
utf8.decode('\xF0\x90\x80\x80'); // -> '\uD800\uDC00'
复制代码

uuid

RFC4122 version 4 compliant uuid generator.

Check RFC4122 4.4 for reference.

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

values

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

Get viewport scale.

viewportScale(); // -> 3
复制代码

waterfall

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

Move a stand-alone function to a worker thread.

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

wrap

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

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]]
复制代码

转载于:https://juejin.im/post/5af04752f265da0b873a6e6a

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值