在業務開發過程當中,咱們常常會重複使用日期格式化、cookie 操做、模板、瀏覽器判斷、類型判斷等功能。爲了不不一樣項目之間進行復制粘貼,能夠將這些經常使用的函數封裝到一塊兒併發布 npm 包。在將近三年的前端開發工做中,筆者將本身平時用到的工具庫通通封裝到了一個項目中 Licia。目前所包含模塊已達三百個,基本能夠知足前端的平常工發需求。若是你對該項目感興趣,歡迎試用並幫忙持續改進:)javascript
首先安裝 npm 包到本地。css
npm i licia --save
複製代碼
安裝完以後,你就能夠直接在項目中引用模塊了,就像使用 lodash 同樣。html
var uuid = require('licia/uuid');
console.log(uuid()); // -> 0e3b84af-f911-4a55-b78a-cedf6f0bd815
複製代碼
該項目自帶打包工具 eustia,能夠經過配置文件或命令行掃描源碼自動生成項目專用的工具庫。前端
npm i eustia -g
複製代碼
假設你想html文件中使用trim方法,先直接在代碼中使用:java
<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>
複製代碼
而後跑下命令:node
eustia build
複製代碼
該工具會掃描你的html代碼並生成一個util.js(默認文件名)文件,大功告成!jquery
PS: 以前作的手機調試工具 eruda 源碼裏的 util.js 就是使用該工具生成的:)linux
你能夠直接訪問 eustia.liriliri.io/builder.htm… 在輸入框輸入須要的工具函數(以空格分隔),而後點擊下載 util.js 文件並將該文件放入項目中去便可。android
好比在小程序中你須要使用時間格式化,直接輸入 dateFormat 後將生成的 util.js 放入小程序源碼中,以後再在代碼裏引用:ios
import { dateFormat } from './util.js';
dateFormat(1525764204163, 'yyyy-mm-dd HH:MM:ss'); // -> '2018-05-08 15:23:24'
複製代碼
jQuery like style dom manipulator.
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...
});
複製代碼
Element attribute manipulation.
Get the value of an attribute for the first element in the set of matched elements.
Name | Type | Desc |
---|---|---|
element | string array element | Elements to manipulate |
name | string | Attribute name |
return | string | Attribute value of first element |
Set one or more attributes for the set of matched elements.
Name | Type | Desc |
---|---|---|
element | string array element | Elements to manipulate |
name | string | Attribute name |
value | string | Attribute value |
Name | Type | Desc |
---|---|---|
element | string array element | Elements to manipulate |
attributes | object | Object of attribute-value pairs to set |
Remove an attribute from each element in the set of matched elements.
Name | Type | Desc |
---|---|---|
element | string array element | Elements to manipulate |
name | string | Attribute name |
$attr('#test', 'attr1', 'test');
$attr('#test', 'attr1'); // -> test
$attr.remove('#test', 'attr1');
$attr('#test', {
'attr1': 'test',
'attr2': 'test'
});
複製代碼
Element class manipulations.
Add the specified class(es) to each element in the set of matched elements.
Name | Type | Desc |
---|---|---|
element | string array element | Elements to manipulate |
names | string array | Classes to add |
Determine whether any of the matched elements are assigned the given class.
Name | Type | Desc |
---|---|---|
element | string array element | Elements to manipulate |
name | string | Class name |
return | boolean | True if elements has given class name |
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.
Name | Type | Desc |
---|---|---|
element | string array element | Elements to manipulate |
name | string | Class name to toggle |
Remove a single class, multiple classes, or all classes from each element in the set of matched elements.
Name | Type | Desc |
---|---|---|
element | string array element | Elements to manipulate |
names | string | Class 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
複製代碼
Element css manipulation.
Get the computed style properties for the first element in the set of matched elements.
Name | Type | Desc |
---|---|---|
element | string array element | Elements to manipulate |
name | string | Property name |
return | string | Css value of first element |
Set one or more CSS properties for the set of matched elements.
Name | Type | Desc |
---|---|---|
element | string array element | Elements to manipulate |
name | string | Property name |
value | string | Css value |
Name | Type | Desc |
---|---|---|
element | string array element | Elements to manipulate |
properties | object | Object of css-value pairs to set |
$css('#test', {
'color': '#fff',
'background': 'black'
});
$css('#test', 'display', 'block');
$css('#test', 'color'); // -> #fff
複製代碼
Wrapper of $attr, adds data- prefix to keys.
$data('#test', 'attr1', 'eustia');
複製代碼
bind events to certain dom elements.
function clickHandler() {
// Do something...
}
$event.on('#test', 'click', clickHandler);
$event.off('#test', 'click', clickHandler);
複製代碼
Insert html on different position.
Insert content before elements.
Insert content after elements.
Insert content to the beginning of elements.
Insert content to the end of elements.
Name | Type | Desc |
---|---|---|
element | string array element | Elements to manipulate |
content | string | Html 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>
複製代碼
Get the position of the element in document.
Name | Type | Desc |
---|---|---|
element | string array element | Elements to get offset |
$offset('#test'); // -> {left: 0, top: 0, width: 0, height: 0}
複製代碼
Element property html, text, val getter and setter.
Get the HTML contents of the first element in the set of matched elements or set the HTML contents of every matched element.
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.
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 the set of matched elements from the DOM.
Name | Type | Desc |
---|---|---|
element | string array element | Elements to delete |
$remove('#test');
複製代碼
Convert value into an array, if it's a string, do querySelector.
Name | Type | Desc |
---|---|---|
value | element array string | Value to convert |
return | array | Array of elements |
$safeEls('.test'); // -> Array of elements with test class
複製代碼
Show elements.
Name | Type | Desc |
---|---|---|
element | string array element | Elements to show |
$show('#test');
複製代碼
Use Blob when available, otherwise BlobBuilder.
Name | Type | Desc |
---|---|---|
parts | array | Blob parts |
[opts] | object | Options |
var blob = new Blob([]);
複製代碼
Create JavaScript class.
Name | Type | Desc |
---|---|---|
methods | object | Public methods |
[statics] | object | Static methods |
return | function | Function 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 converter.
Name | Type | Desc |
---|---|---|
color | string object | Color to convert |
Get color rgb string format.
Get color hex string format.
Get color hsl string format.
[static] Parse color string into object containing value and model.
Name | Type | Desc |
---|---|---|
color | string | Color string |
return | object | Object 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%)'
複製代碼
Flux dispatcher.
var dispatcher = new Dispatcher();
dispatcher.register(function (payload) {
switch (payload.actionType)
{
// Do something
}
});
dispatcher.dispatch({
actionType: 'action'
});
複製代碼
Event emitter class which provides observer pattern.
Bind event.
Unbind event.
Bind event that trigger once.
Name | Type | Desc |
---|---|---|
event | string | Event name |
listener | function | Event listener |
Emit event.
Name | Type | Desc |
---|---|---|
event | string | Event name |
...args | * | Arguments passed to listener |
[static] Mixin object class methods.
Name | Type | Desc |
---|---|---|
obj | object | Object to mixin |
var event = new Emitter();
event.on('test', function () { console.log('test') });
event.emit('test'); // Logs out 'test'.
Emitter.mixin({});
複製代碼
Enum type implementation.
Name | Type | Desc |
---|---|---|
arr | array | Array of strings |
Name | Type | Desc |
---|---|---|
obj | object | Pairs of key and value |
var importance = new Enum([
'NONE', 'TRIVIAL', 'REGULAR', 'IMPORTANT', 'CRITICAL'
]);
if (val === importance.CRITICAL)
{
// Do something.
}
複製代碼
Json to json transformer.
Name | Type | Desc |
---|---|---|
[data={}] | object | Json object to manipulate |
Set object value.
Name | Type | Desc |
---|---|---|
[key] | string | Object key |
val | * | Value to set |
If key is not given, the whole source object is replaced by val.
Get object value.
Name | Type | Desc |
---|---|---|
[key] | string | Object key |
return | * | Specified value or whole object |
Name | Type | Desc |
---|---|---|
key | array string | Object keys to remove |
Shortcut for array map.
Name | Type | Desc |
---|---|---|
from | string | From object path |
to | string | Target object path |
fn | function | Function invoked per iteration |
Shortcut for array filter.
Compute value from several object values.
Name | Type | Desc |
---|---|---|
from | array string | Source values |
to | string | Target object path |
fn | function | Function 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}
複製代碼
Doubly-linked list implementation.
Add an value to the end of the list.
Name | Type | Desc |
---|---|---|
val | * | Value to push |
return | number | Current size |
Get the last value of the list.
Add an value to the head of the list.
Get the first value of the list.
Iterate over the list.
Convert the list to a JavaScript array.
var linkedList = new LinkedList();
linkedList.push(5);
linkedList.pop(); // -> 5
複製代碼
LocalStorage wrapper.
Extend from Store.
Name | Type | Desc |
---|---|---|
name | string | LocalStorage item name |
data | object | Default data |
var store = new LocalStore('licia');
store.set('name', 'licia');
複製代碼
Simple logger with level filter.
Name | Type | Desc |
---|---|---|
name | string | Logger name |
[level=DEBUG] | number | Logger level |
Name | Type | Desc |
---|---|---|
level | number string | Logger level |
Get current level.
Logging methods.
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.
});
複製代碼
Safe MutationObserver, does nothing if MutationObserver is not supported.
var observer = new MutationObserver(function (mutations) {
// Do something.
});
observer.observe(document.htmlElement);
observer.disconnect();
複製代碼
Lightweight Promise implementation.
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 data structure.
Clear the queue.
Add an item to the queue.
Name | Type | Desc |
---|---|---|
item | * | Item to enqueue |
return | number | Current size |
Remove the first item of the queue.
Get the first item without removing it.
Iterate over the queue.
Name | Type | Desc |
---|---|---|
iteratee | function | Function invoked iteration |
[ctx] | * | Function context |
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
複製代碼
Simplified redux like state container.
Name | Type | Desc |
---|---|---|
reducer | function | Function returns next state |
initialState | * | Initial state |
Add a change listener.
Name | Type | Desc |
---|---|---|
listener | function | Callback to invoke on every dispatch |
return | function | Function to unscribe |
Dispatch an action.
Name | Type | Desc |
---|---|---|
action | object | Object representing changes |
return | object | Same action object |
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
複製代碼
Simple wrapper of querySelectorAll to make dom selection easier.
Name | Type | Desc |
---|---|---|
selector | string | Dom selector string |
Get desdendants of current matched elements.
Name | Type | Desc |
---|---|---|
selector | string | Dom selector string |
Iterate over matched elements.
Name | Type | Desc |
---|---|---|
fn | function | Function to execute for each element |
var $test = new Select('#test');
$test.find('.test').each(function (idx, element) {
// Manipulate dom nodes
});
複製代碼
SessionStorage wrapper.
Extend from Store.
Name | Type | Desc |
---|---|---|
name | string | SessionStorage item name |
data | object | Default data |
var store = new SessionStore('licia');
store.set('name', 'licia');
複製代碼
Stack data structure.
Clear the stack.
Add an item to the stack.
Name | Type | Desc |
---|---|---|
item | * | Item to add |
return | number | Current size |
Get the last item of the stack.
Get the last item without removing it.
Iterate over the stack.
Name | Type | Desc |
---|---|---|
iteratee | function | Function invoked iteration |
[ctx] | * | Function context |
Convert the stack to a JavaScript stack.
var stack = new Stack();
stack.push(2); // -> 1
stack.push(3); // -> 2
stack.pop(); // -> 3
複製代碼
Simple state machine.
Extend from Emitter.
Name | Type | Desc |
---|---|---|
initial | string | Initial state |
events | string | Events to change state |
Check current state.
Name | Type | Desc |
---|---|---|
value | string | State to check |
return | boolean | True 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');
複製代碼
Memory storage.
Extend from Emitter.
Name | Type | Desc |
---|---|---|
data | object | Initial data |
Set value.
Name | Type | Desc |
---|---|---|
key | string | Value key |
val | * | Value to set |
Set values.
Name | Type | Desc |
---|---|---|
vals | object | Key value pairs |
This emit a change event whenever is called.
Get value.
Name | Type | Desc |
---|---|---|
key | string | Value key |
return | * | Value of given key |
Get values.
Name | Type | Desc |
---|---|---|
keys | array | Array of keys |
return | object | Key value pairs |
Remove value.
Name | Type | Desc |
---|---|---|
key | string array | Key to remove |
Clear all data.
Iterate over values.
Name | Type | Desc |
---|---|---|
fn | function | Function 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 engine for JavaScript animations.
Extend from Emitter.
Name | Type | Desc |
---|---|---|
obj | object | Values to tween |
Name | Type | Desc |
---|---|---|
destination | obj | Final properties |
duration | number | Tween duration |
ease | string function | Easing function |
Begin playing forward.
Pause the animation.
Get animation paused state.
Update or get animation progress.
Name | Type | Desc |
---|---|---|
[progress] | number | Number 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();
複製代碼
Simple url manipulator.
Name | Type | Desc |
---|---|---|
url=location | string | Url string |
Set query value.
Name | Type | Desc |
---|---|---|
name | string | Query name |
value | string | Query value |
return | Url | this |
Name | Type | Desc |
---|---|---|
names | object | query object |
return | Url | this |
Remove query value.
Name | Type | Desc |
---|---|---|
name | string array | Query name |
return | Url | this |
[static] Parse url into an object.
Name | Type | Desc |
---|---|---|
url | string | Url string |
return | object | Url object |
[static] Stringify url object into a string.
Name | Type | Desc |
---|---|---|
url | object | Url object |
return | string | Url string |
An url object contains the following properties:
Name | Desc |
---|---|
protocol | The protocol scheme of the URL (e.g. http:) |
slashes | A boolean which indicates whether the protocol is followed by two forward slashes (//) |
auth | Authentication information portion (e.g. username:password) |
hostname | Host name without port number |
port | Optional port number |
pathname | URL path |
query | Parsed object containing query string |
hash | The "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'
複製代碼
Object values validation.
Name | Type | Desc |
---|---|---|
options | object | Validation configuration |
Validate object.
Name | Type | Desc |
---|---|---|
obj | object | Object to validate |
return | * | Validation result, true means ok |
[static] Add plugin.
Name | Type | Desc |
---|---|---|
name | string | Plugin name |
plugin | function | Validation handler |
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
複製代碼
Calculate the set of unique abbreviations for a given set of strings.
Name | Type | Desc |
---|---|---|
...arr | string | List of names |
return | object | Abbreviation map |
abbrev('lina', 'luna');
// -> {li: 'lina', lin: 'lina', lina: 'lina', lu: 'luna', lun: 'luna', luna: 'luna'}
複製代碼
Create a function that invokes once it's called n or more times.
Name | Type | Desc |
---|---|---|
n | number | Number of calls before invoked |
fn | function | Function to restrict |
return | function | New restricted function |
var fn = after(5, function() {
// -> Only invoke after fn is called 5 times.
});
複製代碼
Perform an asynchronous HTTP request.
Name | Type | Desc |
---|---|---|
options | object | Ajax options |
Available options:
Name | Type | Desc |
---|---|---|
url | string | Request url |
data | string object | Request data |
dataType=json | string | Response type(json, xml) |
contentType=application/x-www-form-urlencoded | string | Request header Content-Type |
success | function | Success callback |
error | function | Error callback |
complete | function | Callback after request |
timeout | number | Request timeout |
Shortcut for type = GET;
Shortcut for type = POST;
Name | Type | Desc |
---|---|---|
url | string | Request url |
[data] | string object | Request data |
success | function | Success callback |
dataType | function | Response type |
ajax({
url: 'http://example.com',
data: {test: 'true'},
error: function () {},
success: function (data) {
// ...
},
dataType: 'json'
});
ajax.get('http://example.com', {}, function (data) {
// ...
});
複製代碼
Retrieve all the names of object's own and inherited properties.
Name | Type | Desc |
---|---|---|
obj | object | Object to query |
return | array | Array 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']
複製代碼
Make an object map using array of strings.
Name | Type | Desc |
---|---|---|
arr | array | Array of strings |
val=true | * | Key value |
return | object | Object map |
var needPx = arrToMap([
'column-count', 'columns', 'font-weight', 'line-weight', 'opacity', 'z-index', 'zoom'
]);
if (needPx[key]) val += 'px';
複製代碼
Use Buffer to emulate atob when running in node.
atob('SGVsbG8gV29ybGQ='); // -> 'Hello World'
複製代碼
Get average value of given numbers.
Name | Type | Desc |
---|---|---|
...num | number | Numbers to calculate |
return | number | Average value |
average(5, 3, 1); // -> 3
複製代碼
Basic base64 encoding and decoding.
Turn a byte array into a base64 string.
Name | Type | Desc |
---|---|---|
arr | array | Byte array |
return | string | Base64 string |
base64.encode([168, 174, 155, 255]); // -> 'qK6b/w=='
複製代碼
Turn a base64 string into a byte array.
Name | Type | Desc |
---|---|---|
str | string | Base64 string |
return | array | Byte array |
base64.decode('qK6b/w=='); // -> [168, 174, 155, 255]
複製代碼
Create a function that invokes less than n times.
Name | Type | Desc |
---|---|---|
n | number | Number of calls at which fn is no longer invoked |
fn | function | Function to restrict |
return | function | New 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.
複製代碼
Create a function bound to a given object.
Name | Type | Desc |
---|---|---|
fn | function | Function to bind |
ctx | * | This binding of given fn |
[...rest] | * | Optional arguments |
return | function | New 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.'
複製代碼
Use Buffer to emulate btoa when running in node.
btoa('Hello World'); // -> 'SGVsbG8gV29ybGQ='
複製代碼
Bubble sort implementation.
Name | Type | Desc |
---|---|---|
arr | array | Array to sort |
[cmp] | function | Comparator |
bubbleSort([2, 1]); // -> [1, 2]
複製代碼
Convert a function that returns a Promise to a function following the error-first callback style.
Name | Type | Desc |
---|---|---|
fn | function | Function that returns a Promise |
return | function | Function following the error-fist callback style |
function fn() {
return new Promise(function (resolve, reject) {
// ...
});
}
var cbFn = callbackify(fn);
cbFn(function (err, value) {
// ...
});
複製代碼
Convert string to "camelCase".
Name | Type | Desc |
---|---|---|
str | string | String to convert |
return | string | Camel cased string |
camelCase('foo-bar'); // -> fooBar
camelCase('foo bar'); // -> fooBar
camelCase('foo_bar'); // -> fooBar
camelCase('foo.bar'); // -> fooBar
複製代碼
Convert the first character to upper case and the remaining to lower case.
Name | Type | Desc |
---|---|---|
str | string | String to capitalize |
return | string | Capitalized string |
capitalize('rED'); // -> Red
複製代碼
Cast value into a property path array.
Name | Type | Desc |
---|---|---|
str | * | Value to inspect |
[obj] | object | Object to query |
return | array | Property 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']
複製代碼
Center align text in a string.
Name | Type | Desc |
---|---|---|
str | string array | String to align |
[width] | number | Total width of each line |
return | string | Center aligned string |
centerAlign('test', 8); // -> ' test'
centerAlign('test\nlines', 8); // -> ' test\n lines'
centerAlign(['test', 'lines'], 8); // -> ' test\n lines'
複製代碼
Return string representing a character whose Unicode code point is the given integer.
Name | Type | Desc |
---|---|---|
num | number | Integer to convert |
return | string | String representing corresponding char |
char(65); // -> 'A'
char(97); // -> 'a'
複製代碼
Split array into groups the length of given size.
Name | Type | Desc |
---|---|---|
arr | array | Array to process |
size=1 | number | Length 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 number within the inclusive lower and upper bounds.
Name | Type | Desc |
---|---|---|
n | number | Number to clamp |
[lower] | number | Lower bound |
upper | number | Upper bound |
return | number | Clamped number |
clamp(-10, -5, 5); // -> -5
clamp(10, -5, 5); // -> 5
clamp(2, -5, 5); // -> 2
clamp(10, 5); // -> 5
clamp(2, 5); // -> 2
複製代碼
Utility for conditionally joining class names.
Name | Type | Desc |
---|---|---|
...class | string object array | Class names |
return | string | Joined 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';
複製代碼
Create a shallow-copied clone of the provided plain object.
Any nested objects or arrays will be copied by reference, not duplicated.
Name | Type | Desc |
---|---|---|
val | * | Value to clone |
return | * | Cloned value |
clone({name: 'eustia'}); // -> {name: 'eustia'}
複製代碼
Recursively clone value.
Name | Type | Desc |
---|---|---|
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
複製代碼
Compare version strings.
Name | Type | Desc |
---|---|---|
v1 | string | Version to compare |
v2 | string | Version to compare |
return | number | Comparison 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
複製代碼
Return a copy of the array with all falsy values removed.
The values false, null, 0, "", undefined, and NaN are falsey.
Name | Type | Desc |
---|---|---|
arr | array | Array to compact |
return | array | New array of filtered values |
compact([0, 1, false, 2, '', 3]); // -> [1, 2, 3]
複製代碼
Compose a list of functions.
Each function consumes the return value of the function that follows.
Name | Type | Desc |
---|---|---|
...fn | function | Functions to compose |
return | function | Composed function |
var welcome = compose(function (name) {
return 'hi: ' + name;
}, function (name) {
return name.toUpperCase() + '!';
});
welcome('licia'); // -> 'hi: LICIA!'
複製代碼
Compress image using canvas.
Name | Type | Desc |
---|---|---|
file | File Blob | Image file |
opts | object | Options |
cb | function | Callback |
Available options:
Name | Type | Desc |
---|---|---|
maxWidth | number | Max width |
maxHeight | number | Max height |
width | number | Output image width |
height | number | Output image height |
mineType | string | Mine type |
quality=0.8 | number | Image 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 multiple arrays into a single array.
Name | Type | Desc |
---|---|---|
...arr | array | Arrays to concat |
return | array | Concatenated array |
concat([1, 2], [3], [4, 5]); // -> [1, 2, 3, 4, 5]
複製代碼
Check if the value is present in the list.
Name | Type | Desc |
---|---|---|
array | array object | Target list |
value | * | Value to check |
return | boolean | True if value is present in the list |
contain([1, 2, 3], 1); // -> true
contain({a: 1, b: 2}, 1); // -> true
複製代碼
Convert base of a number.
Name | Type | Desc |
---|---|---|
num | number string | Number to convert |
from | number | Base from |
to | number | Base to |
return | string | Converted number |
convertBase('10', 2, 10); // -> '2'
convertBase('ff', 16, 2); // -> '11111111'
複製代碼
Simple api for handling browser cookies.
Get cookie value.
Name | Type | Desc |
---|---|---|
key | string | Cookie key |
return | string | Corresponding cookie value |
Set cookie value.
Name | Type | Desc |
---|---|---|
key | string | Cookie key |
val | string | Cookie value |
[options] | object | Cookie options |
return | exports | Module cookie |
Remove cookie value.
Name | Type | Desc |
---|---|---|
key | string | Cookie key |
[options] | object | Cookie options |
return | exports | Module cookie |
cookie.set('a', '1', {path: '/'});
cookie.get('a'); // -> '1'
cookie.remove('a');
複製代碼
Copy text to clipboard using document.execCommand.
Name | Type | Desc |
---|---|---|
text | string | Text to copy |
[cb] | function | Optional callback |
copy('text', function (err) {
// Handle errors.
});
複製代碼
Used to create extend, extendOwn and defaults.
Name | Type | Desc |
---|---|---|
keysFn | function | Function to get object keys |
defaults | boolean | No override when set to true |
return | function | Result function, extend... |
CreateObjectURL wrapper.
Name | Type | Desc |
---|---|---|
data | File Blob string array | Url data |
[opts] | object | Used when data is not a File or Blob |
return | string | Blob url |
createUrl('test', {type: 'text/plain'}); // -> Blob url
createUrl(['test', 'test']);
createUrl(new Blob([]));
createUrl(new File(['test'], 'test.txt'));
複製代碼
Check if browser supports a given CSS feature.
Name | Type | Desc |
---|---|---|
name | string | Css property name |
[val] | string | Css property value |
return | boolean | True if supports |
cssSupports('display', 'flex'); // -> true
cssSupports('display', 'invalid'); // -> false
cssSupports('text-decoration-line', 'underline'); // -> true
cssSupports('grid'); // -> true
cssSupports('invalid'); // -> false
複製代碼
Function currying.
Name | Type | Desc |
---|---|---|
fn | function | Function to curry |
return | function | New curried function |
var add = curry(function (a, b) { return a + b });
var add1 = add(1);
add1(2); // -> 3
複製代碼
Simple but extremely useful date format function.
Name | Type | Desc |
---|---|---|
[date=new Date] | Date | Date object to format |
mask | string | Format mask |
[utc=false] | boolean | UTC or not |
[gmt=false] | boolean | GMT or not |
Mask | Description |
---|---|
d | Day of the month as digits; no leading zero for single-digit days |
dd | Day of the month as digits; leading zero for single-digit days |
ddd | Day of the week as a three-letter abbreviation |
dddd | Day of the week as its full name |
m | Month as digits; no leading zero for single-digit months |
mm | Month as digits; leading zero for single-digit months |
mmm | Month as a three-letter abbreviation |
mmmm | Month as its full name |
yy | Year as last two digits; leading zero for years less than 10 |
yyyy | Year represented by four digits |
h | Hours; no leading zero for single-digit hours (12-hour clock) |
hh | Hours; leading zero for single-digit hours (12-hour clock) |
H | Hours; no leading zero for single-digit hours (24-hour clock) |
HH | Hours; leading zero for single-digit hours (24-hour clock) |
M | Minutes; no leading zero for single-digit minutes |
MM | Minutes; leading zero for single-digit minutes |
s | Seconds; no leading zero for single-digit seconds |
ss | Seconds; leading zero for single-digit seconds |
l L | Milliseconds. l gives 3 digits. L gives 2 digits |
t | Lowercase, single-character time marker string: a or p |
tt | Lowercase, two-character time marker string: am or pm |
T | Uppercase, single-character time marker string: A or P |
TT | Uppercase, two-character time marker string: AM or PM |
Z | US timezone abbreviation, e.g. EST or MDT |
o | GMT/UTC timezone offset, e.g. -0500 or +0230 |
S | The 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
複製代碼
Return a new debounced version of the passed function.
Name | Type | Desc |
---|---|---|
fn | function | Function to debounce |
wait | number | Number of milliseconds to delay |
return | function | New debounced function |
$(window).resize(debounce(calLayout, 300));
複製代碼
A tiny JavaScript debugging utility.
Name | Type | Desc |
---|---|---|
name | string | Namespace |
return | function | Function to print decorated log |
var d = debug('test');
d('doing lots of uninteresting work');
d.enabled = false;
複製代碼
Better decodeURIComponent that does not throw if input is invalid.
Name | Type | Desc |
---|---|---|
str | string | String to decode |
return | string | Decoded string |
decodeUriComponent('%%25%'); // -> '%%%'
decodeUriComponent('%E0%A4%A'); // -> '\xE0\xA4%A'
複製代碼
Fill in undefined properties in object with the first value present in the following list of defaults objects.
Name | Type | Desc |
---|---|---|
obj | object | Destination object |
*src | object | Sources objects |
return | object | Destination object |
defaults({name: 'RedHood'}, {name: 'Unknown', age: 24}); // -> {name: 'RedHood', age: 24}
複製代碼
Define a module, should be used along with use.
Name | Type | Desc |
---|---|---|
name | string | Module name |
[requires] | array | Dependencies |
method | function | Module 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;
});
複製代碼
Shortcut for Object.defineProperty(defineProperties).
Name | Type | Desc |
---|---|---|
obj | object | Object to define |
prop | string | Property path |
descriptor | object | Property descriptor |
return | object | Object itself |
Name | Type | Desc |
---|---|---|
obj | object | Object to define |
prop | object | Property descriptors |
return | object | Object 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
複製代碼
Invoke function after certain milliseconds.
Name | Type | Desc |
---|---|---|
fn | function | Function to delay |
wait | number | Number of milliseconds to delay invocation |
[...args] | * | Arguments to invoke fn with |
delay(function (text) {
console.log(text);
}, 1000, 'later');
// -> Logs 'later' after one second
複製代碼
Event delegation.
Add event delegation.
Name | Type | Desc |
---|---|---|
el | element | Parent element |
type | string | Event type |
selector | string | Match selector |
cb | function | Event callback |
Remove event delegation.
var container = document.getElementById('container');
function clickHandler() {
// Do something...
}
delegate.add(container, 'click', '.children', clickHandler);
delegate.remove(container, 'click', '.children', clickHandler);
複製代碼
Detect browser info using ua.
Name | Type | Desc |
---|---|---|
[ua=navigator.userAgent] | string | Browser userAgent |
return | object | Object 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...
}
複製代碼
Detect operating system using ua.
Name | Type | Desc |
---|---|---|
[ua=navigator.userAgent] | string | Browser userAgent |
return | string | Operating system name |
Supported os: windows, os x, linux, ios, android, windows phone
if (detectOs() === 'ios')
{
// Do something about ios...
}
複製代碼
Create an array of unique array values not included in the other given array.
Name | Type | Desc |
---|---|---|
arr | array | Array to inspect |
[...rest] | array | Values to exclude |
return | array | New array of filtered values |
difference([3, 2, 1], [4, 2]); // -> [3, 1]
複製代碼
Convert string to "dotCase".
Name | Type | Desc |
---|---|---|
str | string | String to convert |
return | string | Dot cased string |
dotCase('fooBar'); // -> foo.bar
dotCase('foo bar'); // -> foo.bar
複製代碼
Trigger a file download on client side.
Name | Type | Desc |
---|---|---|
data | Blob File string array | Data to download |
name | string | File name |
type=text/plain | string | Data type |
download('test', 'test.txt');
複製代碼
Iterate over elements of collection and invokes iteratee for each element.
Name | Type | Desc |
---|---|---|
obj | object array | Collection to iterate over |
iteratee | function | Function invoked per iteration |
[ctx] | * | Function context |
each({'a': 1, 'b': 2}, function (val, key) {});
複製代碼
Easing functions adapted from http://jqueryui.com/
Name | Type | Desc |
---|---|---|
percent | number | Number between 0 and 1 |
return | number | Calculated number |
easing.linear(0.5); // -> 0.5
easing.inElastic(0.5, 500); // -> 0.03125
複製代碼
Check if string ends with the given target string.
Name | Type | Desc |
---|---|---|
str | string | The string to search |
suffix | string | String suffix |
return | boolean | True if string ends with target |
endWith('ab', 'b'); // -> true
複製代碼
Escapes a string for insertion into HTML, replacing &, <, >, ", `, and ' characters.
Name | Type | Desc |
---|---|---|
str | string | String to escape |
return | string | Escaped string |
escape('You & Me'); -> // -> 'You & Me'
複製代碼
Escape string to be a valid JavaScript string literal between quotes.
http://www.ecma-international.org/ecma-262/5.1/#sec-7.8.4
Name | Type | Desc |
---|---|---|
str | string | String to escape |
return | string | Escaped string |
escapeJsStr('\"\n'); // -> '\\"\\\\n'
複製代碼
Escape special chars to be used as literals in RegExp constructors.
Name | Type | Desc |
---|---|---|
str | string | String to escape |
return | string | Escaped string |
escapeRegExp('[licia]'); // -> '\\[licia\\]'
複製代碼
Load css into page.
Name | Type | Desc |
---|---|---|
css | string | Css code |
evalCss('body{background:#08c}');
複製代碼
Execute js in given context.
Name | Type | Desc |
---|---|---|
js | string | JavaScript code |
[ctx=global] | object | Context |
evalJs('5+2'); // -> 7
evalJs('this.a', {a: 2}); // -> 2
複製代碼
Check if predicate return truthy for all elements.
Name | Type | Desc |
---|---|---|
obj | array object | Collection to iterate over |
predicate | function | Function invoked per iteration |
ctx | * | Predicate context |
return | boolean | True if all elements pass the predicate check |
every([2, 4], function (val) {
return val % 2 === 0;
}); // -> false
複製代碼
Copy all of the properties in the source objects over to the destination object.
Name | Type | Desc |
---|---|---|
obj | object | Destination object |
...src | object | Sources objects |
return | object | Destination object |
extend({name: 'RedHood'}, {age: 24}); // -> {name: 'RedHood', age: 24}
複製代碼
Recursive object extending.
Name | Type | Desc |
---|---|---|
obj | object | Destination object |
...src | object | Sources objects |
return | object | Destination object |
extendDeep({
name: 'RedHood',
family: {
mother: 'Jane',
father: 'Jack'
}
}, {
family: {
brother: 'Bruce'
}
});
// -> {name: 'RedHood', family: {mother: 'Jane', father: 'Jack', brother: 'Bruce'}}
複製代碼
Like extend, but only copies own properties over to the destination object.
Name | Type | Desc |
---|---|---|
obj | object | Destination object |
*src | object | Sources objects |
return | object | Destination object |
extendOwn({name: 'RedHood'}, {age: 24}); // -> {name: 'RedHood', age: 24}
複製代碼
Extract block comments from source code.
Name | Type | Desc |
---|---|---|
str | string | String to extract |
return | array | Block comments |
extractBlockCmts('\/*licia*\/'); // -> ['licia']
複製代碼
Extract urls from plain text.
Name | Type | Desc |
---|---|---|
str | string | Text to extract |
return | array | Url list |
var str = '[Official site: http://eustia.liriliri.io](http://eustia.liriliri.io)';
extractUrl(str); // -> ['http://eustia.liriliri.io']
複製代碼
Turn XMLHttpRequest into promise like.
Note: This is not a complete fetch pollyfill.
Name | Type | Desc |
---|---|---|
url | string | Request url |
options | object | Request options |
return | promise | Request promise |
fetch('test.json', {
method: 'GET',
timeout: 3000,
headers: {},
body: ''
}).then(function (res) {
return res.json();
}).then(function (data) {
console.log(data);
});
複製代碼
Calculate fibonacci number.
Name | Type | Desc |
---|---|---|
n | number | Index of fibonacci sequence |
return | number | Expected fibonacci number |
fibonacci(1); // -> 1
fibonacci(3); // -> 2
複製代碼
Turn bytes into human readable file size.
Name | Type | Desc |
---|---|---|
bytes | number | File bytes |
return | string | Readable file size |
fileSize(5); // -> '5'
fileSize(1500); // -> '1.46K'
fileSize(1500000); // -> '1.43M'
fileSize(1500000000); // -> '1.4G'
fileSize(1500000000000); // -> '1.36T'
複製代碼
Fill elements of array with value.
Name | Type | Desc |
---|---|---|
arr | array | Array to fill |
val | * | Value to fill array with |
start=0 | number | Start position |
end=arr.length | number | End position |
return | array | Filled array |
fill([1, 2, 3], '*'); // -> ['*', '*', '*']
fill([1, 2, 3], '*', 1, 2); // -> [1, '*', 3]
複製代碼
Iterates over elements of collection, returning an array of all the values that pass a truth test.
Name | Type | Desc |
---|---|---|
obj | array | Collection to iterate over |
predicate | function | Function invoked per iteration |
[ctx] | * | Predicate context |
return | array | Array of all values that pass predicate |
filter([1, 2, 3, 4, 5], function (val) {
return val % 2 === 0;
}); // -> [2, 4]
複製代碼
Find the first value that passes a truth test in a collection.
Name | Type | Desc |
---|---|---|
obj | array object | Collection to iterate over |
predicate | function | Function 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}
複製代碼
Return the first index where the predicate truth test passes.
Name | Type | Desc |
---|---|---|
arr | array | Array to search |
predicate | function | Function invoked per iteration |
return | number | Index of matched element |
findIdx([{
name: 'john',
age: 24
}, {
name: 'jane',
age: 23
}], function (val) {
return val.age === 23;
}); // -> 1
複製代碼
Return the first key where the predicate truth test passes.
Name | Type | Desc |
---|---|---|
obj | object | Object to search |
predicate | function | Function invoked per iteration |
[ctx] | * | Predicate context |
return | string | Key of matched element |
findKey({a: 1, b: 2}, function (val) {
return val === 1;
}); // -> a
複製代碼
Return the last index where the predicate truth test passes.
Name | Type | Desc |
---|---|---|
arr | array | Array to search |
predicate | function | Function invoked per iteration |
return | number | Last index of matched element |
findLastIdx([{
name: 'john',
age: 24
}, {
name: 'jane',
age: 23
}, {
name: 'kitty',
age: 24
}], function (val) {
return val.age === 24;
}); // -> 2
複製代碼
Recursively flatten an array.
Name | Type | Desc |
---|---|---|
arr | array | Array to flatten |
return | array | New flattened array |
flatten(['a', ['b', ['c']], 'd', ['e']]); // -> ['a', 'b', 'c', 'd', 'e']
複製代碼
Get a function parameter's names.
Name | Type | Desc |
---|---|---|
fn | function | Function to get parameters |
return | array | Names |
fnParams(function (a, b) {}); // -> ['a', 'b']
複製代碼
Format string in a printf-like format.
Name | Type | Desc |
---|---|---|
str | string | String to format |
...values | * | Values to replace format specifiers |
return | string | Formatted string |
Specifier | Desc |
---|---|
%s | String |
%d, %i | Integer |
%f | Floating point value |
%o | Object |
format('%s_%s', 'foo', 'bar'); // -> 'foo bar'
複製代碼
Convert number to fraction.
Name | Type | Desc |
---|---|---|
num | number | Number to convert |
return | string | Corresponding fraction |
fraction(1.2); // -> '6/5'
複製代碼
Shortcut for Object.freeze.
Use Object.defineProperties if Object.freeze is not supported.
Name | Type | Desc |
---|---|---|
obj | object | Object to freeze |
return | object | Object passed in |
var a = {b: 1};
freeze(a);
a.b = 2;
console.log(a); // -> {b: 1}
複製代碼
Recursively use Object.freeze.
Name | Type | Desc |
---|---|---|
obj | object | Object to freeze |
return | object | Object passed in |
var a = {b: {c: 1}};
freezeDeep(a);
a.b.c = 2;
console.log(a); // -> {b: {c: 1}}
複製代碼
Compute the greatest common divisor using Euclid's algorithm.
Name | Type | Desc |
---|---|---|
a | number | Number to calculate |
b | number | Number to calculate |
return | number | Greatest common divisor |
gcd(121, 44); // -> 11
複製代碼
Get url param.
Name | Type | Desc |
---|---|---|
name | string | Param name |
url=location | string | Url to get param |
return | string | Param value |
getUrlParam('test', 'http://example.com/?test=true'); // -> 'true'
複製代碼
Checks if key is a direct property.
Name | Type | Desc |
---|---|---|
obj | object | Object to query |
key | string | Path to check |
return | boolean | True if key is a direct property |
has({one: 1}, 'one'); // -> true
複製代碼
Capture keyboard input to trigger given events.
Register keyboard listener.
Name | Type | Desc |
---|---|---|
key | string | Key string |
listener | function | Key listener |
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);
複製代碼
Convert hsl to rgb.
Name | Type | Desc |
---|---|---|
hsl | array | Hsl values |
return | array | Rgb values |
hslToRgb([165, 59, 50, 0.8]); // -> [52, 203, 165, 0.8]
複製代碼
Return the first argument given.
Name | Type | Desc |
---|---|---|
val | * | Any value |
return | * | Given value |
identity('a'); // -> 'a'
複製代碼
Get the index at which the first occurrence of value.
Name | Type | Desc |
---|---|---|
arr | array | Array to search |
val | * | Value to search for |
fromIdx=0 | number | Index to search from |
idxOf([1, 2, 1, 2], 2, 2); // -> 3
複製代碼
Indent each line in a string.
Name | Type | Desc |
---|---|---|
str | string | String to indent |
[char] | string | Character to prepend |
[len] | number | Indent length |
return | string | Indented string |
indent('foo\nbar', ' ', 4); // -> 'foo\n bar'
複製代碼
Inherit the prototype methods from one constructor into another.
Name | Type | Desc |
---|---|---|
Class | function | Child Class |
SuperClass | function | Super 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'
複製代碼
Insertion sort implementation.
Name | Type | Desc |
---|---|---|
arr | array | Array to sort |
[cmp] | function | Comparator |
insertionSort([2, 1]); // -> [1, 2]
複製代碼
Compute the list of values that are the intersection of all the arrays.
Name | Type | Desc |
---|---|---|
...arr | array | Arrays to inspect |
return | array | New array of inspecting values |
intersect([1, 2, 3, 4], [2, 1, 10], [2, 1]); // -> [1, 2]
複製代碼
Intersect two ranges.
Name | Type | Desc |
---|---|---|
a | object | Range a |
b | object | Range b |
return | object | Intersection 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
複製代碼
Create an object composed of the inverted keys and values of object.
Name | Type | Desc |
---|---|---|
obj | object | Object to invert |
return | object | New 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'}
複製代碼
Check if an url is absolute.
Name | Type | Desc |
---|---|---|
url | string | Url to check |
return | boolean | True if url is absolute |
isAbsoluteUrl('http://www.surunzi.com'); // -> true
isAbsoluteUrl('//www.surunzi.com'); // -> false
isAbsoluteUrl('surunzi.com'); // -> false
複製代碼
Check if value is classified as an arguments object.
Name | Type | Desc |
---|---|---|
val | * | Value to check |
return | boolean | True if value is an arguments object |
(function () {
isArgs(arguments); // -> true
})();
複製代碼
Check if value is an Array
object.
Name | Type | Desc |
---|---|---|
val | * | Value to check |
return | boolean | True if value is an Array object |
isArr([]); // -> true
isArr({}); // -> false
複製代碼
Check if value is an ArrayBuffer.
Name | Type | Desc |
---|---|---|
val | * | Value to check |
return | boolean | True if value is an ArrayBuffer |
isArrBuffer(new ArrayBuffer(8)); // -> true
複製代碼
Check if value is array-like.
Name | Type | Desc |
---|---|---|
val | * | Value to check |
return | boolean | True if value is array like |
Function returns false.
isArrLike('test'); // -> true
isArrLike(document.body.children); // -> true;
isArrLike([1, 2, 3]); // -> true
複製代碼
Check if value is a Blob.
Name | Type | Desc |
---|---|---|
val | * | Value to check |
return | boolean | True if value is a Blob |
isBlob(new Blob([])); // -> true;
isBlob([]); // -> false
複製代碼
Check if value is a boolean primitive.
Name | Type | Desc |
---|---|---|
val | * | Value to check |
return | boolean | True if value is a boolean |
isBool(true); // -> true
isBool(false); // -> true
isBool(1); // -> false
複製代碼
Check if running in a browser.
console.log(isBrowser); // -> true if running in a browser
複製代碼
Check if value is a buffer.
Name | Type | Desc |
---|---|---|
val | * | The value to check |
return | boolean | True if value is a buffer |
isBuffer(new Buffer(4)); // -> true
複製代碼
Check if values are close(almost equal) to each other.
abs(a-b) <= max(relTol * max(abs(a), abs(b)), absTol)
Name | Type | Desc |
---|---|---|
a | number | Number to compare |
b | number | Number to compare |
relTol=1e-9 | number | Relative tolerance |
absTol=0 | number | Absolute tolerance |
return | boolean | True 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
複製代碼
Check if a string is a valid data url.
Name | Type | Desc |
---|---|---|
str | string | String to check |
return | boolean | True if string is a data url |
isDataUrl('http://eustia.liriliri.io'); // -> false
isDataUrl('data:text/plain;base64,SGVsbG8sIFdvcmxkIQ%3D%3D'); // -> true
複製代碼
Check if value is classified as a Date object.
Name | Type | Desc |
---|---|---|
val | * | value to check |
return | boolean | True if value is a Date object |
isDate(new Date()); // -> true
複製代碼
Check if value is a DOM element.
Name | Type | Desc |
---|---|---|
val | * | Value to check |
return | boolean | True if value is a DOM element |
isEl(document.body); // -> true
複製代碼
Loosely validate an email address.
Name | Type | Desc |
---|---|---|
val | string | Value to check |
return | boolean | True if value is an email like string |
isEmail('surunzi@foxmail.com'); // -> true
複製代碼
Check if value is an empty object or array.
Name | Type | Desc |
---|---|---|
val | * | Value to check |
return | boolean | True if value is empty |
isEmpty([]); // -> true
isEmpty({}); // -> true
isEmpty(''); // -> true
複製代碼
Performs an optimized deep comparison between the two objects, to determine if they should be considered equal.
Name | Type | Desc |
---|---|---|
val | * | Value to compare |
other | * | Other value to compare |
return | boolean | True if values are equivalent |
isEqual([1, 2, 3], [1, 2, 3]); // -> true
複製代碼
Check if value is an error.
Name | Type | Desc |
---|---|---|
val | * | Value to check |
return | boolean | True if value is an error |
isErr(new Error()); // -> true
複製代碼
Check if number is even.
Name | Type | Desc |
---|---|---|
num | number | Number to check |
return | boolean | True if number is even |
isOdd(0); // -> true
isOdd(1); // -> false
isOdd(2); // -> true
複製代碼
Check if value is a file.
Name | Type | Desc |
---|---|---|
val | * | Value to check |
return | boolean | True if value is a file |
isFile(new File(['test'], "test.txt", {type: "text/plain"})); // -> true
複製代碼
Check if value is a finite primitive number.
Name | Type | Desc |
---|---|---|
val | * | Value to check |
return | boolean | True if value is a finite number |
isFinite(3); // -> true
isFinite(Infinity); // -> false
複製代碼
Check if value is a function.
Name | Type | Desc |
---|---|---|
val | * | Value to check |
return | boolean | True if value is a function |
Generator function is also classified as true.
isFn(function() {}); // -> true
isFn(function*() {}); // -> true
複製代碼
Check if value is a generator function.
Name | Type | Desc |
---|---|---|
val | * | Value to check |
return | boolean | True if value is a generator function |
isGeneratorFn(function * () {}); // -> true;
isGeneratorFn(function () {}); // -> false;
複製代碼
Checks if value is classified as a Integer.
Name | Type | Desc |
---|---|---|
val | * | Value to check |
return | boolean | True if value is correctly classified |
isInt(5); // -> true
isInt(5.1); // -> false
isInt({}); // -> false
複製代碼
Check if value is a valid JSON.
It uses JSON.parse()
and a try... catch
block.
Name | Type | Desc |
---|---|---|
val | string | JSON string |
return | boolean | True if value is a valid JSON |
isJson('{"a": 5}'); // -> true
isJson("{'a': 5}"); // -> false
複製代碼
Check if a year is a leap year.
Name | Type | Desc |
---|---|---|
year | number | Year to check |
return | boolean | True if year is a leap year |
isLeapYear(2000); // -> true
isLeapYear(2002); // -> false
複製代碼
Check if keys and values in src are contained in obj.
Name | Type | Desc |
---|---|---|
obj | object | Object to inspect |
src | object | Object of property values to match |
return | boolean | True if object is match |
isMatch({a: 1, b: 2}, {a: 1}); // -> true
複製代碼
Check if running in wechat mini program.
console.log(isMiniProgram); // -> true if running in mini program.
複製代碼
Check whether client is using a mobile browser using ua.
Name | Type | Desc |
---|---|---|
[ua=navigator.userAgent] | string | User agent |
return | boolean | True if ua belongs to mobile browsers |
isMobile(navigator.userAgent);
複製代碼
Check if value is an NaN.
Name | Type | Desc |
---|---|---|
val | * | Value to check |
return | boolean | True if value is an NaN |
Undefined is not an NaN, different from global isNaN function.
isNaN(0); // -> false
isNaN(NaN); // -> true
複製代碼
Check if value is a native function.
Name | Type | Desc |
---|---|---|
val | * | Value to check |
return | boolean | True if value is a native function |
isNative(function () {}); // -> false
isNative(Math.min); // -> true
複製代碼
Check if value is null or undefined, the same as value == null.
Name | Type | Desc |
---|---|---|
val | * | Value to check |
return | boolean | True if value is null or undefined |
isNil(null); // -> true
isNil(void 0); // -> true
isNil(undefined); // -> true
isNil(false); // -> false
isNil(0); // -> false
isNil([]); // -> false
複製代碼
Check if running in node.
console.log(isNode); // -> true if running in node
複製代碼
Check if value is an Null.
Name | Type | Desc |
---|---|---|
val | * | Value to check |
return | boolean | True if value is an Null |
isNull(null); // -> true
複製代碼
Check if value is classified as a Number primitive or object.
Name | Type | Desc |
---|---|---|
val | * | Value to check |
return | boolean | True if value is correctly classified |
isNum(5); // -> true
isNum(5.1); // -> true
isNum({}); // -> false
複製代碼
Check if value is numeric.
Name | Type | Desc |
---|---|---|
val | * | Value to check |
return | boolean | True 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
複製代碼
Check if value is the language type of Object.
Name | Type | Desc |
---|---|---|
val | * | Value to check |
return | boolean | True if value is an object |
isObj({}); // -> true
isObj([]); // -> true
複製代碼
Check if number is odd.
Name | Type | Desc |
---|---|---|
num | number | Number to check |
return | boolean | True if number is odd |
isOdd(0); // -> false
isOdd(1); // -> true
isOdd(2); // -> false
複製代碼
Check if value is an object created by Object constructor.
Name | Type | Desc |
---|---|---|
val | * | Value to check |
return | boolean | True if value is a plain object |
isPlainObj({}); // -> true
isPlainObj([]); // -> false
isPlainObj(function () {}); // -> false
複製代碼
Check if value is string, number, boolean or null.
Name | Type | Desc |
---|---|---|
val | * | Value to check |
return | boolean | True if value is a primitive |
isPrimitive(5); // -> true
isPrimitive('abc'); // -> true
isPrimitive(false); // -> true
複製代碼
Check if value looks like a promise.
Name | Type | Desc |
---|---|---|
val | * | Value to check |
return | boolean | True if value looks like a promise |
isPromise(new Promise(function () {})); // -> true
isPromise({}); // -> false
複製代碼
Check if value is a regular expression.
Name | Type | Desc |
---|---|---|
val | * | Value to check |
return | boolean | True if value is a regular expression |
isRegExp(/a/); // -> true
複製代碼
Check if path appears to be relative.
Name | Type | Desc |
---|---|---|
path | string | Path to check |
return | boolean | True if path appears to be relative |
isRelative('README.md'); // -> true
複製代碼
Determine if running on a high DPR device or not.
console.log(isRetina); // -> true if high DPR
複製代碼
Check if value is a string primitive.
Name | Type | Desc |
---|---|---|
val | * | Value to check |
return | boolean | True if value is a string primitive |
isStr('licia'); // -> true
複製代碼
Check if value is a Node.js stream.
Name | Type | Desc |
---|---|---|
val | * | Value to check |
return | boolean | True if value is a Node.js stream |
var stream = require('stream');
isStream(new stream.Stream()); // -> true
複製代碼
Check if value is a typed array.
Name | Type | Desc |
---|---|---|
val | * | Value to check |
return | boolean | True if value is a typed array |
isTypedArr([]); // -> false
isTypedArr(new Unit8Array); // -> true
複製代碼
Check if value is undefined.
Name | Type | Desc |
---|---|---|
val | * | Value to check |
return | boolean | True if value is undefined |
isUndef(void 0); // -> true
isUndef(null); // -> false
複製代碼
Loosely validate an url.
Name | Type | Desc |
---|---|---|
val | string | Value to check |
return | boolean | True if value is an url like string |
isUrl('http://www.example.com?foo=bar¶m=test'); // -> true
複製代碼
Check if platform is windows.
console.log(isWindows); // -> true if running on windows
複製代碼
A simple jsonp implementation.
Name | Type | Desc |
---|---|---|
opts | object | Jsonp Options |
Available options:
Name | Type | Desc |
---|---|---|
url | string | Request url |
data | object | Request data |
success | function | Success callback |
param=callback | string | Callback param |
name | string | Callback name |
error | function | Error callback |
complete | function | Callback after request |
timeout | number | Request timeout |
jsonp({
url: 'http://example.com',
data: {test: 'true'},
success: function (data) {
// ...
}
});
複製代碼
Convert string to "kebabCase".
Name | Type | Desc |
---|---|---|
str | string | String to convert |
return | string | Kebab cased string |
kebabCase('fooBar'); // -> foo-bar
kebabCase('foo bar'); // -> foo-bar
kebabCase('foo_bar'); // -> foo-bar
kebabCase('foo.bar'); // -> foo-bar
複製代碼
Key codes and key names conversion.
Get key code's name.
Name | Type | Desc |
---|---|---|
code | number | Key code |
return | string | Corresponding key name |
Get key name's code.
Name | Type | Desc |
---|---|---|
name | string | Key name |
return | number | Corresponding key code |
keyCode(13); // -> 'enter'
keyCode('enter'); // -> 13
複製代碼
Create an array of the own enumerable property names of object.
Name | Type | Desc |
---|---|---|
obj | object | Object to query |
return | array | Array of property names |
keys({a: 1}); // -> ['a']
複製代碼
Get the last element of array.
Name | Type | Desc |
---|---|---|
arr | array | The array to query |
return | * | The last element of array |
last([1, 2]); // -> 2
複製代碼
Require modules lazily.
var r = lazyRequire(require);
var _ = r('underscore');
// underscore is required only when _ is called.
_().isNumber(5);
複製代碼
Hyperlink urls in a string.
Name | Type | Desc |
---|---|---|
str | string | String to hyperlink |
[hyperlink] | function | Function to hyperlink url |
return | string | Result 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>';
});
複製代碼
Inject link tag into page with given href value.
Name | Type | Desc |
---|---|---|
src | string | Style source |
cb | function | Onload callback |
loadCss('style.css', function (isLoaded) {
// Do something...
});
複製代碼
Load image with given src.
Name | Type | Desc |
---|---|---|
src | string | Image source |
[cb] | function | Onload callback |
loadImg('http://eustia.liriliri.io/img.jpg', function (err, img) {
console.log(img.width, img.height);
});
複製代碼
Inject script tag into page with given src value.
Name | Type | Desc |
---|---|---|
src | string | Script source |
cb | function | Onload callback |
loadJs('main.js', function (isLoaded) {
// Do something...
});
複製代碼
Get the longest item in an array.
Name | Type | Desc |
---|---|---|
arr | array | Array to inspect |
return | * | Longest item |
longest(['a', 'abcde', 'abc']); // -> 'abcde'
複製代碼
Convert string to lower case.
Name | Type | Desc |
---|---|---|
str | string | String to convert |
return | string | Lower cased string |
lowerCase('TEST'); // -> 'test'
複製代碼
Pad string on the left side if it's shorter than length.
Name | Type | Desc |
---|---|---|
str | string | String to pad |
len | number | Padding length |
[chars] | string | String used as padding |
return | string | Resulted string |
lpad('a', 5); // -> ' a'
lpad('a', 5, '-'); // -> '----a'
lpad('abc', 3, '-'); // -> 'abc'
lpad('abc', 5, 'ab'); // -> 'ababc'
複製代碼
Remove chars or white-spaces from beginning of string.
Name | Type | Desc |
---|---|---|
str | string | String to trim |
chars | string array | Characters to trim |
return | string | Trimmed string |
ltrim(' abc '); // -> 'abc '
ltrim('_abc_', '_'); // -> 'abc_'
ltrim('_abc_', ['a', '_']); // -> 'bc_'
複製代碼
Create an array of values by running each element in collection through iteratee.
Name | Type | Desc |
---|---|---|
obj | array object | Collection to iterate over |
iteratee | function | Function invoked per iteration |
[ctx] | * | Function context |
return | array | New mapped array |
map([4, 8], function (n) { return n * n; }); // -> [16, 64]
複製代碼
Map for objects.
Name | Type | Desc |
---|---|---|
obj | object | Object to iterate over |
iteratee | function | Function invoked per iteration |
[ctx] | * | Function context |
return | object | New mapped object |
mapObj({a: 1, b: 2}, function (val, key) { return val + 1 }); // -> {a: 2, b: 3}
複製代碼
Return a predicate function that checks if attrs are contained in an object.
Name | Type | Desc |
---|---|---|
attrs | object | Object of property values to match |
return | function | New 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 }]
複製代碼
Get maximum value of given numbers.
Name | Type | Desc |
---|---|---|
...num | number | Numbers to calculate |
return | number | Maximum value |
max(2.3, 1, 4.5, 2); // 4.5
複製代碼
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 a given function by caching the computed result.
Name | Type | Desc |
---|---|---|
fn | function | Function to have its output memoized |
[hashFn] | function | Function to create cache key |
return | function | New memoized function |
var fibonacci = memoize(function(n) {
return n < 2 ? n : fibonacci(n - 1) + fibonacci(n - 2);
});
複製代碼
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.
Name | Type | Desc |
---|---|---|
[name] | string array | Meta name |
return | string | Meta content |
Set meta content.
Name | Type | Desc |
---|---|---|
name | string | Meta name |
content | string | Meta content |
Name | Type | Desc |
---|---|---|
metas | object | Object of name content pairs |
Remove metas.
Name | Type | Desc |
---|---|---|
name | string array | Meta 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']);
複製代碼
Return a sorted list of the names of every method in an object.
Name | Type | Desc |
---|---|---|
obj | object | Object to check |
return | array | Function names in object |
methods(console); // -> ['Console', 'assert', 'dir', ...]
複製代碼
Get minimum value of given numbers.
Name | Type | Desc |
---|---|---|
...num | number | Numbers to calculate |
return | number | Minimum value |
min(2.3, 1, 4.5, 2); // 1
複製代碼
Recursively create directories.
Name | Type | Desc |
---|---|---|
dir | string | Directory to create |
[mode=0777] | number | Directory mode |
callback | function | Callback |
mkdir('/tmp/foo/bar/baz', function (err) {
if (err) console.log(err);
else console.log('Done');
});
複製代碼
Tiny moment.js like implementation.
It only supports a subset of moment.js api.
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
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'
複製代碼
Convert time string formats to milliseconds.
Turn time string into milliseconds.
Name | Type | Desc |
---|---|---|
str | string | String format |
return | number | Milliseconds |
Turn milliseconds into time string.
Name | Type | Desc |
---|---|---|
num | number | Milliseconds |
return | string | String 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'
複製代碼
Create a function that negates the result of the predicate function.
Name | Type | Desc |
---|---|---|
predicate | function | Predicate to negate |
return | function | New function |
function even(n) { return n % 2 === 0 }
filter([1, 2, 3, 4, 5, 6], negate(even)); // -> [1, 3, 5]
複製代碼
Next tick for both node and browser.
Name | Type | Desc |
---|---|---|
cb | function | Function to call |
Use process.nextTick if available.
Otherwise setImmediate or setTimeout is used as fallback.
nextTick(function () {
// Do something...
});
複製代碼
A no-operation function.
noop(); // Does nothing
複製代碼
Normalize file path slashes.
Name | Type | Desc |
---|---|---|
path | string | Path to normalize |
return | string | Normalized path |
normalizePath('\\foo\\bar\\'); // -> '/foo/bar/'
normalizePath('./foo//bar'); // -> './foo/bar'
複製代碼
Gets the number of milliseconds that have elapsed since the Unix epoch.
now(); // -> 1468826678701
複製代碼
Alias of Object.prototype.toString.
Name | Type | Desc |
---|---|---|
value | * | Source value |
return | string | String representation of given value |
objToStr(5); // -> '[object Number]'
複製代碼
Opposite of pick.
Name | Type | Desc |
---|---|---|
obj | object | Source object |
filter | string array function | Object filter |
return | object | Filtered 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
複製代碼
Used for function context binding.
Screen orientation helper.
Bind change event.
Unbind change event.
Get current orientation(landscape or portrait).
orientation.on('change', function (direction) {
console.log(direction); // -> 'portrait'
});
orientation.get(); // -> 'landscape'
複製代碼
Pad string on the left and right sides if it's shorter than length.
Name | Type | Desc |
---|---|---|
str | string | String to pad |
len | number | Padding length |
chars | string | String used as padding |
return | string | Resulted string |
pad('a', 5); // -> ' a '
pad('a', 5, '-'); // -> '--a--'
pad('abc', 3, '-'); // -> 'abc'
pad('abc', 5, 'ab'); // -> 'babca'
pad('ab', 5, 'ab'); // -> 'ababa'
複製代碼
Convert an object into a list of [key, value] pairs.
Name | Type | Desc |
---|---|---|
obj | object | Object to convert |
return | array | List of [key, value] pairs |
pairs({a: 1, b: 2}); // -> [['a', 1], ['b', 2]]
複製代碼
Run an array of functions in parallel.
Name | Type | Desc |
---|---|---|
tasks | array | Array of functions |
[cb] | function | Callback 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']
});
複製代碼
Parse command line argument options, the same as minimist.
Name | Type | Desc |
---|---|---|
args | array | Argument array |
opts | object | Parse options |
return | object | Parsed result |
Name | Type | Desc |
---|---|---|
names | object | option names |
shorthands | object | option shorthands |
parseArgs(['eustia', '--output', 'util.js', '-w'], {
names: {
output: 'string',
watch: 'boolean'
},
shorthands: {
output: 'o',
watch: 'w'
}
});
// -> {remain: ['eustia'], output: 'util.js', watch: true}
複製代碼
Partially apply a function by filling in given arguments.
Name | Type | Desc |
---|---|---|
fn | function | Function to partially apply arguments to |
...partials | * | Arguments to be partially applied |
return | function | New partially applied function |
var sub5 = partial(function (a, b) { return b - a }, 5);
sub(20); // -> 15
複製代碼
Convert string to "pascalCase".
Name | Type | Desc |
---|---|---|
str | string | String to convert |
return | string | Pascal cased string |
pascalCase('fooBar'); // -> FooBar
pascalCase('foo bar'); // -> FooBar
pascalCase('foo_bar'); // -> FooBar
pascalCase('foo.bar'); // -> FooBar
複製代碼
High resolution time up to microsecond precision.
var start = perfNow();
// Do something.
console.log(perfNow() - start);
複製代碼
Return a filtered copy of an object.
Name | Type | Desc |
---|---|---|
obj | object | Source object |
filter | string array function | Object filter |
return | object | Filtered 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}
複製代碼
Extract a list of property values.
Name | Type | Desc |
---|---|---|
obj | object array | Collection to iterate over |
key | string array | Property path |
return | array | New array of specified property |
var stooges = [
{name: 'moe', age: 40},
{name: 'larry', age: 50},
{name: 'curly', age: 60}
];
pluck(stooges, 'name'); // -> ['moe', 'larry', 'curly']
複製代碼
Find decimal precision of a given number.
Name | Type | Desc |
---|---|---|
num | number | Number to check |
return | number | Precision |
precision(1.234); // -> 3;
複製代碼
Add vendor prefixes to a CSS attribute.
Name | Type | Desc |
---|---|---|
name | string | Property name |
return | string | Prefixed property name |
Create a dasherize version.
prefix('text-emphasis'); // -> 'WebkitTextEmphasis'
prefix.dash('text-emphasis'); // -> '-webkit-text-emphasis'
prefix('color'); // -> 'color'
複製代碼
Convert callback based functions into Promises.
Name | Type | Desc |
---|---|---|
fn | function | Callback based function |
[multiArgs=false] | boolean | If callback has multiple success value |
return | boolean | Result 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.
});
複製代碼
Return a function that will itself return the key property of any passed-in object.
Name | Type | Desc |
---|---|---|
path | string array | Path of the property to get |
return | function | New accessor function |
var obj = {a: {b: 1}};
property('a')(obj); // -> {b: 1}
property(['a', 'b'])(obj); // -> 1
複製代碼
Parse and stringify url query strings.
Parse a query string into an object.
Name | Type | Desc |
---|---|---|
str | string | Query string |
return | object | Query object |
Stringify an object into a query string.
Name | Type | Desc |
---|---|---|
obj | object | Query object |
return | string | Query 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']}
複製代碼
Shortcut for requestAnimationFrame.
Use setTimeout if native requestAnimationFrame is not supported.
var id = raf(function tick() {
// Animation stuff
raf(tick);
});
raf.cancel(id);
複製代碼
Produces a random number between min and max(inclusive).
Name | Type | Desc |
---|---|---|
min | number | Minimum possible value |
max | number | Maximum possible value |
[floating=false] | boolean | Float or not |
return | number | Random 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
複製代碼
Random bytes generator.
Use crypto module in node or crypto object in browser if possible.
Name | Type | Desc |
---|---|---|
size | number | Number of bytes to generate |
return | object | Random bytes of given length |
randomBytes(5); // -> [55, 49, 153, 30, 122]
複製代碼
Create flexibly-numbered lists of integers.
Name | Type | Desc |
---|---|---|
[start] | number | Start of the range |
end | number | End of the range |
step=1 | number | Value to increment or decrement by |
range(5); // -> [0, 1, 2, 3, 4]
range(0, 5, 2) // -> [0, 2, 4]
複製代碼
Invoke callback when dom is ready, similar to jQuery ready.
Name | Type | Desc |
---|---|---|
fn | function | Callback function |
ready(function () {
// It's safe to manipulate dom here.
});
複製代碼
Turn a list of values into a single value.
Name | Type | Desc |
---|---|---|
obj | object array | Collection to iterate over |
[iteratee=identity] | function | Function invoked per iteration |
[initial] | * | Initial value |
[ctx] | * | Function context |
return | * | Accumulated value |
reduce([1, 2, 3], function (sum, n) { return sum + n }, 0); // -> 6
複製代碼
Right-associative version of reduce.
reduceRight([[1], [2], [3]], function (a, b) { return a.concat(b) }, []); // -> [3, 2, 1]
複製代碼
Opposite of filter.
Name | Type | Desc |
---|---|---|
obj | array | Collection to iterate over |
predicate | function | Function invoked per iteration |
[ctx] | * | Predicate context |
return | array | Array of all values that pass predicate |
reject([1, 2, 3, 4, 5], function (val) {
return val % 2 === 0;
}); // -> [1, 3, 5]
複製代碼
Remove all elements from array that predicate returns truthy for and return an array of the removed elements.
Unlike filter, this method mutates array.
Name | Type | Desc |
---|---|---|
obj | array | Collection to iterate over |
predicate | function | Function invoked per iteration |
[ctx] | * | Predicate context |
return | array | Array 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 string n-times.
Name | Type | Desc |
---|---|---|
str | string | String to repeat |
n | number | Repeat times |
return | string | Repeated string |
repeat('a', 3); // -> 'aaa'
repeat('ab', 2); // -> 'abab'
repeat('*', 0); // -> ''
複製代碼
This accumulates the arguments passed into an array, after a given index.
Name | Type | Desc |
---|---|---|
function | function | Function that needs rest parameters |
startIndex | number | The start index to accumulates |
return | function | Generated function with rest parameters |
var paramArr = restArgs(function (rest) { return rest });
paramArr(1, 2, 3, 4); // -> [1, 2, 3, 4]
複製代碼
Convert rgb to hsl.
Name | Type | Desc |
---|---|---|
rgb | array | Rgb values |
return | array | Hsl values |
rgbToHsl([52, 203, 165, 0.8]); // -> [165, 59, 50, 0.8]
複製代碼
Loop through all possible path and domain to remove cookie.
Name | Type | Desc |
---|---|---|
key | string | Cookie key |
rmCookie('test');
複製代碼
Recursively remove directories.
Name | Type | Desc |
---|---|---|
dir | string | Directory to remove |
callback | function | Callback |
rmdir('/tmp/foo/bar/baz', function (err) {
if (err) console.log (err);
else console.log('Done');
});
複製代碼
Root object reference, global
in nodeJs, window
in browser.
Pad string on the right side if it's shorter than length.
Name | Type | Desc |
---|---|---|
str | string | String to pad |
len | number | Padding length |
chars | string | String used as padding |
return | string | Resulted string |
rpad('a', 5); // -> 'a '
rpad('a', 5, '-'); // -> 'a----'
rpad('abc', 3, '-'); // -> 'abc'
rpad('abc', 5, 'ab'); // -> 'abcab'
複製代碼
Remove chars or white-spaces from end of string.
Name | Type | Desc |
---|---|---|
str | string | String to trim |
chars | string array | Characters to trim |
return | string | Trimmed string |
rtrim(' abc '); // -> ' abc'
rtrim('_abc_', '_'); // -> '_abc'
rtrim('_abc_', ['c', '_']); // -> '_ab'
複製代碼
Create callback based on input value.
Delete object property.
Name | Type | Desc |
---|---|---|
obj | object | Object to query |
path | array string | Path 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
複製代碼
Get object property, don't throw undefined error.
Name | Type | Desc |
---|---|---|
obj | object | Object to query |
path | array string | Path 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
複製代碼
Set value at path of object.
If a portion of path doesn't exist, it's created.
Name | Type | Desc |
---|---|---|
obj | object | Object to modify |
path | array string | Path 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}}
複製代碼
Use storage safely in safari private browsing and older browsers.
Name | Type | Desc |
---|---|---|
[type='local'] | string | local or session |
return | object | Specified storage |
var localStorage = safeStorage('local');
localStorage.setItem('licia', 'util');
複製代碼
Sample random values from a collection.
Name | Type | Desc |
---|---|---|
obj | array object | Collection to sample |
n | number | Number of values |
return | array | Array of sample values |
sample([2, 3, 1], 2); // -> [2, 3]
sample({a: 1, b: 2, c: 3}, 1); // -> [2]
複製代碼
Scroll to a target with animation.
Name | Type | Desc |
---|---|---|
target | element string number | Scroll target |
options | object | Scroll options |
Name | Type | Default | Desc |
---|---|---|---|
tolerance | number | 0 | Tolerance of target to scroll |
duration | number | 800 | Scroll duration |
easing | string function | outQuart | Easing function |
callback | function | noop | Function to run once scrolling complete |
scrollTo('body', {
tolerance: 0,
duration: 800,
easing: 'outQuart',
callback: function () {}
});
複製代碼
Selection sort implementation.
Name | Type | Desc |
---|---|---|
arr | array | Array to sort |
[cmp] | function | Comparator |
selectionSort([2, 1]); // -> [1, 2]
複製代碼
Randomize the order of the elements in a given array.
Name | Type | Desc |
---|---|---|
arr | array | Array to randomize |
return | array | Randomized Array |
shuffle([1, 2, 3]); // -> [3, 1, 2]
複製代碼
Get size of object, length of array like object or the number of keys.
Name | Type | Desc |
---|---|---|
obj | array object | Collection to inspect |
return | number | Collection size |
size({a: 1, b: 2}); // -> 2
size([1, 2, 3]); // -> 3
複製代碼
Create slice of source array or array-like object.
Name | Type | Desc |
---|---|---|
array | array | Array to slice |
[start=0] | number | Start position |
[end=array.length] | number | End position, not included |
slice([1, 2, 3, 4], 1, 2); // -> [2]
複製代碼
Convert string to "snakeCase".
Name | Type | Desc |
---|---|---|
str | string | String to convert |
return | string | Snake cased string |
snakeCase('fooBar'); // -> foo_bar
snakeCase('foo bar'); // -> foo_bar
snakeCase('foo.bar'); // -> foo_bar
複製代碼
Check if predicate return truthy for any element.
Name | Type | Desc |
---|---|---|
obj | array object | Collection to iterate over |
predicate | function | Function to invoked per iteration |
ctx | * | Predicate context |
return | boolean | True if any element passes the predicate check |
some([2, 5], function (val) {
return val % 2 === 0;
}); // -> true
複製代碼
Convert string to "spaceCase".
Name | Type | Desc |
---|---|---|
str | string | String to convert |
return | string | Space cased string |
spaceCase('fooBar'); // -> foo bar
spaceCase('foo.bar'); // -> foo bar
spaceCase('foo.bar'); // -> foo bar
複製代碼
Split different string case to an array.
Name | Type | Desc |
---|---|---|
str | string | String to split |
return | array | Result 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']
複製代碼
Split path into device, dir, name and ext.
Name | Type | Desc |
---|---|---|
path | string | Path to split |
return | object | Object 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'}
複製代碼
Check if string starts with the given target string.
Name | Type | Desc |
---|---|---|
str | string | String to search |
prefix | string | String prefix |
return | boolean | True if string starts with prefix |
startWith('ab', 'a'); // -> true
複製代碼
String hash function using djb2.
Name | Type | Desc |
---|---|---|
str | string | String to hash |
return | number | Hash result |
strHash('test'); // -> 2090770981
複製代碼
JSON stringify with support for circular object, function etc.
Undefined is treated as null value.
Name | Type | Desc |
---|---|---|
obj | object | Object to stringify |
spaces | number | Indent spaces |
return | string | Stringified object |
stringify({a: function () {}}); // -> '{"a":"[Function function () {}]"}'
var obj = {a: 1};
obj.b = obj;
stringify(obj); // -> '{"a":1,"b":"[Circular ~]"}'
複製代碼
Strip ansi codes from a string.
Name | Type | Desc |
---|---|---|
str | string | String to strip |
return | string | Resulted string |
stripAnsi('\u001b[4mcake\u001b[0m'); // -> 'cake'
複製代碼
Strip comments from source code.
Name | Type | Desc |
---|---|---|
str | string | Source code |
return | string | Code without comments |
stripCmts('// comment \n var a = 5; /* comment2\n * comment3\n *\/'); // -> ' var a = 5; '
複製代碼
Strip ansi color codes from a string.
Name | Type | Desc |
---|---|---|
str | string | String to strip |
return | string | Resulted string |
stripColor('\u001b[31mred\u001b[39m'); // -> 'red'
複製代碼
Strip html tags from a string.
Name | Type | Desc |
---|---|---|
str | string | String to strip |
return | string | Resulted string |
stripHtmlTag('<p>Hello</p>'); // -> 'Hello'
複製代碼
Compute sum of given numbers.
Name | Type | Desc |
---|---|---|
...num | number | Numbers to calculate |
return | number | Sum of numbers |
sum(1, 2, 5); // -> 8
複製代碼
Compile JavaScript template into function that can be evaluated for rendering.
Name | Type | String |
---|---|---|
str | string | Template string |
return | function | Compiled template function |
template('Hello <%= name %>!')({name: 'licia'}); // -> 'Hello licia!'
template('<p><%- name %></p>')({name: '<licia>'}); // -> '<p><licia></p>'
template('<%if (echo) {%>Hello licia!<%}%>')({echo: true}); // -> 'Hello licia!'
複製代碼
Return a new throttled version of the passed function.
Name | Type | Desc |
---|---|---|
fn | function | Function to throttle |
wait | number | Number of milliseconds to delay |
return | function | New throttled function |
$(window).scroll(throttle(updatePos, 100));
複製代碼
Tiny wrapper of stream Transform.
Name | Type | Desc |
---|---|---|
[opts={}] | Object | Options to initialize stream |
transform | function | Transform implementation |
[flush] | function | Flush implementation |
Shortcut for setting objectMode to true.
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'));
複製代碼
Format datetime with *** time ago statement.
Name | Type | Desc |
---|---|---|
date | Date | Date to calculate |
[now=new Date] | Date | Current date |
return | string | Formatted 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
複製代碼
Get execution time of a function.
Name | Type | Desc |
---|---|---|
fn | function | Function to measure time |
return | number | Execution time, ms |
timeTaken(function () {
// Do something.
}); // -> Time taken to execute given function.
複製代碼
Convert value to an array.
Name | Type | Desc |
---|---|---|
val | * | Value to convert |
return | array | Converted array |
toArr({a: 1, b: 2}); // -> [{a: 1, b: 2}]
toArr('abc'); // -> ['abc']
toArr(1); // -> [1]
toArr(null); // -> []
複製代碼
Convert value to a boolean.
Name | Type | Desc |
---|---|---|
val | * | Value to convert |
return | boolean | Converted boolean |
toBool(true); // -> true
toBool(null); // -> false
toBool(1); // -> true
toBool(0); // -> false
toBool('0'); // -> false
toBool('1'); // -> true
toBool('false'); // -> false
複製代碼
Convert value to a Date.
Name | Type | Desc |
---|---|---|
val | * | Value to convert |
return | Date | Converted Date |
toDate('20180501');
toDate('2018-05-01');
toDate(1525107450849);
複製代碼
Convert html string to dom elements.
There should be only one root element.
Name | Type | Desc |
---|---|---|
str | string | Html string |
return | element | Html element |
toEl('<div>test</div>');
複製代碼
Convert value to an integer.
Name | Type | Desc |
---|---|---|
val | * | Value to convert |
return | number | Converted integer |
toInt(1.1); // -> 1
toInt(undefined); // -> 0
複製代碼
Convert value to a number.
Name | Type | Desc |
---|---|---|
val | * | Value to process |
return | number | Resulted number |
toNum('5'); // -> 5
複製代碼
Convert function to its source code.
Name | Type | Desc |
---|---|---|
fn | function | Function to convert |
return | string | Source code |
toSrc(Math.min); // -> 'function min() { [native code] }'
toSrc(function () {}) // -> 'function () { }'
複製代碼
Convert value to a string.
Name | Type | Desc |
---|---|---|
val | * | Value to convert |
return | string | Resulted string |
toStr(null); // -> ''
toStr(1); // -> '1'
toStr(false); // -> 'false'
toStr([1, 2, 3]); // -> '1,2,3'
複製代碼
Topological sorting algorithm.
Name | Type | Desc |
---|---|---|
edges | array | Dependencies |
return | array | Sorted order |
topoSort([[1, 2], [1, 3], [3, 2]]); // -> [1, 3, 2]
複製代碼
Trigger browser events.
Name | Type | Desc |
---|---|---|
[el=document] | element | Element to trigger |
type | string | Event type |
opts | object | Options |
trigger(el, 'mouseup');
trigger('keydown', {keyCode: 65});
複製代碼
Remove chars or white-spaces from beginning end of string.
Name | Type | Desc |
---|---|---|
str | string | String to trim |
chars | string array | Characters to trim |
return | string | Trimmed string |
trim(' abc '); // -> 'abc'
trim('_abc_', '_'); // -> 'abc'
trim('_abc_', ['a', 'c', '_']); // -> 'b'
複製代碼
Run function in a try catch.
Name | Type | Desc |
---|---|---|
fn | function | Function to try catch |
[cb] | function | Callback |
tryIt(function () {
// Do something that might cause an error.
}, function (err, result) {
if (err) console.log(err);
});
複製代碼
Determine the internal JavaScript [[Class]] of an object.
Name | Type | Desc |
---|---|---|
val | * | Value to get type |
return | string | Type of object, lowercased |
type(5); // -> 'number'
type({}); // -> 'object'
type(function () {}); // -> 'function'
type([]); // -> 'array'
複製代碼
UCS-2 encoding and decoding.
Create a string using an array of code point values.
Name | Type | Desc |
---|---|---|
arr | array | Array of code points |
return | string | Encoded string |
Create an array of code point values using a string.
Name | Type | Desc |
---|---|---|
str | string | Input string |
return | array | Array of code points |
ucs2.encode([0x61, 0x62, 0x63]); // -> 'abc'
ucs2.decode('abc'); // -> [0x61, 0x62, 0x63]
'𝌆'.length; // -> 2
ucs2.decode('𝌆').length; // -> 1
複製代碼
Convert HTML entities back, the inverse of escape.
Name | Type | Desc |
---|---|---|
str | string | String to unescape |
return | string | unescaped string |
unescape('You & Me'); -> // -> 'You & Me'
複製代碼
Create an array of unique values, in order, from all given arrays.
Name | Type | Desc |
---|---|---|
...arr | array | Arrays to inspect |
return | array | New array of combined values |
union([2, 1], [4, 2], [1, 2]); // -> [2, 1, 4]
複製代碼
Generate a globally-unique id.
Name | Type | Desc |
---|---|---|
prefix | string | Id prefix |
return | string | Globally-unique id |
uniqId('eusita_'); // -> 'eustia_xxx'
複製代碼
Create duplicate-free version of an array.
Name | Type | Desc |
---|---|---|
arr | array | Array to inspect |
[compare] | function | Function for comparing values |
return | array | New duplicate free array |
unique([1, 2, 3, 1]); // -> [1, 2, 3]
複製代碼
Opposite of zip.
Name | Type | Desc |
---|---|---|
arr | array | Array of grouped elements to process |
return | array | New array of regrouped elements |
unzip([['a', 1, true], ['b', 2, false]]); // -> [['a', 'b'], [1, 2], [true, false]]
複製代碼
Convert string to upper case.
Name | Type | Desc |
---|---|---|
str | string | String to convert |
return | string | Uppercased string |
upperCase('test'); // -> 'TEST'
複製代碼
Convert the first character of string to upper case.
Name | Type | Desc |
---|---|---|
str | string | String to convert |
return | string | Converted string |
upperFirst('red'); // -> Red
複製代碼
Use modules that is created by define.
Name | Type | Desc |
---|---|---|
[requires] | array | Dependencies |
method | function | Codes to be executed |
define('A', function () {
return 'A';
});
use(['A'], function (A) {
console.log(A + 'B'); // -> 'AB'
});
複製代碼
UTF-8 encoding and decoding.
Turn any UTF-8 decoded string into UTF-8 encoded string.
Name | Type | Desc |
---|---|---|
str | string | String to encode |
return | string | Encoded string |
Name | Type | Desc |
---|---|---|
str | string | String to decode |
[safe=false] | boolean | Suppress error if true |
return | string | Decoded 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'
複製代碼
RFC4122 version 4 compliant uuid generator.
Check RFC4122 4.4 for reference.
uuid(); // -> '53ce0497-6554-49e9-8d79-347406d2a88b'
複製代碼
Create an array of the own enumerable property values of object.
Name | Type | Desc |
---|---|---|
obj | object | Object to query |
return | array | Array of property values |
values({one: 1, two: 2}); // -> [1, 2]
複製代碼
Get viewport scale.
viewportScale(); // -> 3
複製代碼
Run an array of functions in series.
Name | Type | Desc |
---|---|---|
tasks | array | Array of functions |
[cb] | function | Callback once completed |
waterfall([
function (cb) {
cb(null, 'one');
},
function (arg1, cb) {
// arg1 -> 'one'
cb(null, 'done');
}
], function (err, result) {
// result -> 'done'
});
複製代碼
Move a stand-alone function to a worker thread.
Name | Type | Desc |
---|---|---|
fn | function | Function to turn |
return | function | Workerized Function |
workerize(function (a, b) {
return a + b;
});
workerize(1, 2).then(function (value) {
console.log(value); // -> 3
});
複製代碼
Wrap the function inside a wrapper function, passing it as the first argument.
Name | Type | Desc |
---|---|---|
fn | * | Function to wrap |
wrapper | function | Wrapper function |
return | function | New function |
var p = wrap(escape, function(fn, text) {
return '<p>' + fn(text) + '</p>';
});
p('You & Me'); // -> '<p>You & Me</p>'
複製代碼
Merge together the values of each of the arrays with the values at the corresponding position.
Name | Type | Desc |
---|---|---|
*arr | array | Arrays to process |
return | array | New array of grouped elements |
zip(['a', 'b'], [1, 2], [true, false]); // -> [['a', 1, true], ['b', 2, false]]
複製代碼