javascript
Licia:最全最实用的 JavaScript 工具库
前言
在業務開發過程中,我們經常會重復使用日期格式化、cookie 操作、模板、瀏覽器判斷、類型判斷等功能。為了避免不同項目之間進行復制粘貼,可以將這些常用的函數封裝到一起并發布 npm 包。在將近三年的前端開發工作中,筆者將自己平時用到的工具庫統統封裝到了一個項目中 Licia。目前所包含模塊已達三百個,基本可以滿足前端的日常工發需求。如果你對該項目感興趣,歡迎試用并幫忙持續改進:)
使用方法
一、安裝 npm 包
首先安裝 npm 包到本地。
npm i licia --save 復制代碼安裝完之后,你就可以直接在項目中引用模塊了,就像使用 lodash 一樣。
var uuid = require('licia/uuid');console.log(uuid()); // -> 0e3b84af-f911-4a55-b78a-cedf6f0bd815 復制代碼二、使用打包工具
該項目自帶打包工具 eustia,可以通過配置文件或命令行掃描源碼自動生成項目專用的工具庫。
npm i eustia -g 復制代碼假設你想html文件中使用trim方法,先直接在代碼中使用:
<html> <head><meta charset="utf-8"/><title>Eustia</title><script src="util.js"></script> </head> <body><script>var projectName = _.trim(' Eustia ');// Some code...</script> </body> </html> 復制代碼然后跑下命令:
eustia build 復制代碼該工具會掃描你的html代碼并生成一個util.js(默認文件名)文件,大功告成!
PS: 之前做的手機調試工具 eruda 源碼里的 util.js 就是使用該工具生成的:)
三、使用在線工具生成 util 庫
你可以直接訪問 eustia.liriliri.io/builder.htm… 在輸入框輸入需要的工具函數(以空格分隔),然后點擊下載 util.js 文件并將該文件放入項目中去即可。
比如在小程序中你需要使用時間格式化,直接輸入 dateFormat 后將生成的 util.js 放入小程序源碼中,之后再在代碼里引用:
import { dateFormat } from './util.js';dateFormat(1525764204163, 'yyyy-mm-dd HH:MM:ss'); // -> '2018-05-08 15:23:24' 復制代碼支持模塊匯總
$
jQuery like style dom manipulator.
Available methods
offset, hide, show, first, last, get, eq, on, off, html, text, val, css, attr, data, rmAttr, remove, addClass, rmClass, toggleClass, hasClass, append, prepend, before, after
var $btn = $('#btn'); $btn.html('eustia'); $btn.addClass('btn'); $btn.show(); $btn.on('click', function () {// Do something... }); 復制代碼$attr
Element attribute manipulation.
Get the value of an attribute for the first element in the set of matched elements.
| 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.
| element | string array element | Elements to manipulate |
| name | string | Attribute name |
| value | string | Attribute value |
| element | string array element | Elements to manipulate |
| attributes | object | Object of attribute-value pairs to set |
remove
Remove an attribute from each element in the set of matched elements.
| element | string array element | Elements to manipulate |
| name | string | Attribute name |
$class
Element class manipulations.
add
Add the specified class(es) to each element in the set of matched elements.
| element | string array element | Elements to manipulate |
| names | string array | Classes to add |
has
Determine whether any of the matched elements are assigned the given class.
| element | string array element | Elements to manipulate |
| name | string | Class name |
| return | boolean | True if elements has given class name |
toggle
Add or remove one or more classes from each element in the set of matched elements, depending on either the class's presence or the value of the state argument.
| element | string array element | Elements to manipulate |
| name | string | Class name to toggle |
remove
Remove a single class, multiple classes, or all classes from each element in the set of matched elements.
| element | string array element | Elements to manipulate |
| names | string | Class names to remove |
$css
Element css manipulation.
Get the computed style properties for the first element in the set of matched elements.
| 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.
| element | string array element | Elements to manipulate |
| name | string | Property name |
| value | string | Css value |
| element | string array element | Elements to manipulate |
| properties | object | Object of css-value pairs to set |
$data
Wrapper of $attr, adds data- prefix to keys.
$data('#test', 'attr1', 'eustia'); 復制代碼$event
bind events to certain dom elements.
function clickHandler() {// Do something... } $event.on('#test', 'click', clickHandler); $event.off('#test', 'click', clickHandler); 復制代碼$insert
Insert html on different position.
before
Insert content before elements.
after
Insert content after elements.
prepend
Insert content to the beginning of elements.
append
Insert content to the end of elements.
| element | string array element | Elements to manipulate |
| content | string | Html strings |
$offset
Get the position of the element in document.
| element | string array element | Elements to get offset |
$property
Element property html, text, val getter and setter.
html
Get the HTML contents of the first element in the set of matched elements or set the HTML contents of every matched element.
text
Get the combined text contents of each element in the set of matched elements, including their descendants, or set the text contents of the matched elements.
val
Get the current value of the first element in the set of matched elements or set the value of every matched element.
$property.html('#test', 'licia'); $property.html('#test'); // -> licia 復制代碼$remove
Remove the set of matched elements from the DOM.
| element | string array element | Elements to delete |
$safeEls
Convert value into an array, if it's a string, do querySelector.
| value | element array string | Value to convert |
| return | array | Array of elements |
$show
Show elements.
| element | string array element | Elements to show |
Blob
Use Blob when available, otherwise BlobBuilder.
constructor
| parts | array | Blob parts |
| [opts] | object | Options |
Class
Create JavaScript class.
| methods | object | Public methods |
| [statics] | object | Static methods |
| return | function | Function used to create instances |
Color
Color converter.
constructor
| color | string object | Color to convert |
toRgb
Get color rgb string format.
toHex
Get color hex string format.
toHsl
Get color hsl string format.
parse
[static] Parse color string into object containing value and model.
| color | string | Color string |
| return | object | Object containing value and model |
Dispatcher
Flux dispatcher.
Related docs.
var dispatcher = new Dispatcher();dispatcher.register(function (payload) {switch (payload.actionType){// Do something} });dispatcher.dispatch({actionType: 'action' }); 復制代碼Emitter
Event emitter class which provides observer pattern.
on
Bind event.
off
Unbind event.
once
Bind event that trigger once.
| event | string | Event name |
| listener | function | Event listener |
emit
Emit event.
| event | string | Event name |
| ...args | * | Arguments passed to listener |
mixin
[static] Mixin object class methods.
| obj | object | Object to mixin |
Enum
Enum type implementation.
constructor
| arr | array | Array of strings |
| obj | object | Pairs of key and value |
JsonTransformer
Json to json transformer.
constructor
| [data={}] | object | Json object to manipulate |
set
Set object value.
| [key] | string | Object key |
| val | * | Value to set |
If key is not given, the whole source object is replaced by val.
get
Get object value.
| [key] | string | Object key |
| return | * | Specified value or whole object |
remove
| key | array string | Object keys to remove |
map
Shortcut for array map.
| from | string | From object path |
| to | string | Target object path |
| fn | function | Function invoked per iteration |
filter
Shortcut for array filter.
compute
Compute value from several object values.
| from | array string | Source values |
| to | string | Target object path |
| fn | function | Function to compute target value |
LinkedList
Doubly-linked list implementation.
push
Add an value to the end of the list.
| val | * | Value to push |
| return | number | Current size |
pop
Get the last value of the list.
unshift
Add an value to the head of the list.
shift
Get the first value of the list.
forEach
Iterate over the list.
toArr
Convert the list to a JavaScript array.
var linkedList = new LinkedList(); linkedList.push(5); linkedList.pop(); // -> 5 復制代碼LocalStore
LocalStorage wrapper.
Extend from Store.
constructor
| name | string | LocalStorage item name |
| data | object | Default data |
Logger
Simple logger with level filter.
constructor
| name | string | Logger name |
| [level=DEBUG] | number | Logger level |
setLevel
| level | number string | Logger level |
getLevel
Get current level.
trace, debug, info, warn, error
Logging methods.
Log Levels
TRACE, DEBUG, INFO, WARN, ERROR and SILENT.
var logger = new Logger('licia', Logger.level.ERROR); logger.trace('test');// Format output. logger.formatter = function (type, argList) {argList.push(new Date().getTime());return argList; };logger.on('all', function (type, argList) {// It's not affected by log level. });logger.on('debug', function (argList) {// Affected by log level. }); 復制代碼MutationObserver
Safe MutationObserver, does nothing if MutationObserver is not supported.
var observer = new MutationObserver(function (mutations) {// Do something. }); observer.observe(document.htmlElement); observer.disconnect(); 復制代碼Promise
Lightweight Promise implementation.
Promises spec
function get(url) {return new Promise(function (resolve, reject){var req = new XMLHttpRequest();req.open('GET', url);req.onload = function (){req.status == 200 ? resolve(req.reponse) : reject(Error(req.statusText));};req.onerror = function () { reject(Error('Network Error')) };req.send();}); }get('test.json').then(function (result) {// Do something... }); 復制代碼Queue
Queue data structure.
clear
Clear the queue.
enqueue
Add an item to the queue.
| item | * | Item to enqueue |
| return | number | Current size |
dequeue
Remove the first item of the queue.
peek
Get the first item without removing it.
forEach
Iterate over the queue.
| iteratee | function | Function invoked iteration |
| [ctx] | * | Function context |
toArr
Convert queue to a JavaScript array.
var queue = new Queue();console.log(queue.size); // -> 0 queue.enqueue(2); queue.enqueue(3); queue.dequeue(); // -> 2 console.log(queue.size); // -> 1 queue.peek(); // -> 3 console.log(queue.size); // -> 1 復制代碼ReduceStore
Simplified redux like state container.
constructor
| reducer | function | Function returns next state |
| initialState | * | Initial state |
subscribe
Add a change listener.
| listener | function | Callback to invoke on every dispatch |
| return | function | Function to unscribe |
dispatch
Dispatch an action.
| action | object | Object representing changes |
| return | object | Same action object |
getState
Get the current state.
var store = new ReduceStore(function (state, action) {switch (action.type){case 'INCREMENT': return state + 1;case 'DECREMENT': return state - 1;default: return state;} }, 0);store.subscribe(function () {console.log(store.getState()); });store.dispatch({type: 'INCREMENT'}); // 1 store.dispatch({type: 'INCREMENT'}); // 2 store.dispatch({type: 'DECREMENT'}); // 1 復制代碼Select
Simple wrapper of querySelectorAll to make dom selection easier.
constructor
| selector | string | Dom selector string |
find
Get desdendants of current matched elements.
| selector | string | Dom selector string |
each
Iterate over matched elements.
| fn | function | Function to execute for each element |
SessionStore
SessionStorage wrapper.
Extend from Store.
constructor
| name | string | SessionStorage item name |
| data | object | Default data |
Stack
Stack data structure.
clear
Clear the stack.
push
Add an item to the stack.
| item | * | Item to add |
| return | number | Current size |
pop
Get the last item of the stack.
peek
Get the last item without removing it.
forEach
Iterate over the stack.
| iteratee | function | Function invoked iteration |
| [ctx] | * | Function context |
toArr
Convert the stack to a JavaScript stack.
var stack = new Stack();stack.push(2); // -> 1 stack.push(3); // -> 2 stack.pop(); // -> 3 復制代碼State
Simple state machine.
Extend from Emitter.
constructor
| initial | string | Initial state |
| events | string | Events to change state |
is
Check current state.
| value | string | State to check |
| return | boolean | True if current state equals given value |
Store
Memory storage.
Extend from Emitter.
constructor
| data | object | Initial data |
set
Set value.
| key | string | Value key |
| val | * | Value to set |
Set values.
| vals | object | Key value pairs |
This emit a change event whenever is called.
get
Get value.
| key | string | Value key |
| return | * | Value of given key |
Get values.
| keys | array | Array of keys |
| return | object | Key value pairs |
remove
Remove value.
| key | string array | Key to remove |
clear
Clear all data.
each
Iterate over values.
| fn | function | Function invoked per interation |
Tween
Tween engine for JavaScript animations.
Extend from Emitter.
constructor
| obj | object | Values to tween |
to
| destination | obj | Final properties |
| duration | number | Tween duration |
| ease | string function | Easing function |
play
Begin playing forward.
pause
Pause the animation.
paused
Get animation paused state.
progress
Update or get animation progress.
| [progress] | number | Number between 0 and 1 |
Url
Simple url manipulator.
constructor
| url=location | string | Url string |
setQuery
Set query value.
| name | string | Query name |
| value | string | Query value |
| return | Url | this |
| names | object | query object |
| return | Url | this |
rmQuery
Remove query value.
| name | string array | Query name |
| return | Url | this |
parse
[static] Parse url into an object.
| url | string | Url string |
| return | object | Url object |
stringify
[static] Stringify url object into a string.
| url | object | Url object |
| return | string | Url string |
An url object contains the following properties:
| 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 (#) |
Validator
Object values validation.
constructor
| options | object | Validation configuration |
validate
Validate object.
| obj | object | Object to validate |
| return | * | Validation result, true means ok |
addPlugin
[static] Add plugin.
| name | string | Plugin name |
| plugin | function | Validation handler |
Default Plugins
Required, number, boolean, string and regexp.
Validator.addPlugin('custom', function (val, key, config) {if (typeof val === 'string' && val.length === 5) return true;return key + ' should be a string with length 5'; }); var validator = new Validator({'test': {required: true,custom: true} }); validator.validate({}); // -> 'test is required' validator.validate({test: 1}); // -> 'test should be a string with length 5'; validator.validate({test: 'licia'}); // -> true 復制代碼abbrev
Calculate the set of unique abbreviations for a given set of strings.
| ...arr | string | List of names |
| return | object | Abbreviation map |
after
Create a function that invokes once it's called n or more times.
| n | number | Number of calls before invoked |
| fn | function | Function to restrict |
| return | function | New restricted function |
ajax
Perform an asynchronous HTTP request.
| options | object | Ajax options |
Available options:
| 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 |
get
Shortcut for type = GET;
post
Shortcut for type = POST;
| url | string | Request url |
| [data] | string object | Request data |
| success | function | Success callback |
| dataType | function | Response type |
allKeys
Retrieve all the names of object's own and inherited properties.
| 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'] 復制代碼arrToMap
Make an object map using array of strings.
| arr | array | Array of strings |
| val=true | * | Key value |
| return | object | Object map |
atob
Use Buffer to emulate atob when running in node.
atob('SGVsbG8gV29ybGQ='); // -> 'Hello World' 復制代碼average
Get average value of given numbers.
| ...num | number | Numbers to calculate |
| return | number | Average value |
base64
Basic base64 encoding and decoding.
encode
Turn a byte array into a base64 string.
| arr | array | Byte array |
| return | string | Base64 string |
decode
Turn a base64 string into a byte array.
| str | string | Base64 string |
| return | array | Byte array |
before
Create a function that invokes less than n times.
| 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. 復制代碼bind
Create a function bound to a given object.
| fn | function | Function to bind |
| ctx | * | This binding of given fn |
| [...rest] | * | Optional arguments |
| return | function | New bound function |
btoa
Use Buffer to emulate btoa when running in node.
btoa('Hello World'); // -> 'SGVsbG8gV29ybGQ=' 復制代碼bubbleSort
Bubble sort implementation.
| arr | array | Array to sort |
| [cmp] | function | Comparator |
callbackify
Convert a function that returns a Promise to a function following the error-first callback style.
| fn | function | Function that returns a Promise |
| return | function | Function following the error-fist callback style |
camelCase
Convert string to "camelCase".
| str | string | String to convert |
| return | string | Camel cased string |
capitalize
Convert the first character to upper case and the remaining to lower case.
| str | string | String to capitalize |
| return | string | Capitalized string |
castPath
Cast value into a property path array.
| str | * | Value to inspect |
| [obj] | object | Object to query |
| return | array | Property path array |
centerAlign
Center align text in a string.
| str | string array | String to align |
| [width] | number | Total width of each line |
| return | string | Center aligned string |
char
Return string representing a character whose Unicode code point is the given integer.
| num | number | Integer to convert |
| return | string | String representing corresponding char |
chunk
Split array into groups the length of given size.
| arr | array | Array to process |
| size=1 | number | Length of each chunk |
clamp
Clamp number within the inclusive lower and upper bounds.
| n | number | Number to clamp |
| [lower] | number | Lower bound |
| upper | number | Upper bound |
| return | number | Clamped number |
className
Utility for conditionally joining class names.
| ...class | string object array | Class names |
| return | string | Joined class names |
clone
Create a shallow-copied clone of the provided plain object.
Any nested objects or arrays will be copied by reference, not duplicated.
| val | * | Value to clone |
| return | * | Cloned value |
cloneDeep
Recursively clone value.
| val | * | Value to clone |
| return | * | Deep cloned Value |
cmpVersion
Compare version strings.
| v1 | string | Version to compare |
| v2 | string | Version to compare |
| return | number | Comparison result |
compact
Return a copy of the array with all falsy values removed.
The values false, null, 0, "", undefined, and NaN are falsey.
| arr | array | Array to compact |
| return | array | New array of filtered values |
compose
Compose a list of functions.
Each function consumes the return value of the function that follows.
| ...fn | function | Functions to compose |
| return | function | Composed function |
compressImg
Compress image using canvas.
| file | File Blob | Image file |
| opts | object | Options |
| cb | function | Callback |
Available options:
| 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
Concat multiple arrays into a single array.
| ...arr | array | Arrays to concat |
| return | array | Concatenated array |
contain
Check if the value is present in the list.
| array | array object | Target list |
| value | * | Value to check |
| return | boolean | True if value is present in the list |
convertBase
Convert base of a number.
| num | number string | Number to convert |
| from | number | Base from |
| to | number | Base to |
| return | string | Converted number |
cookie
Simple api for handling browser cookies.
get
Get cookie value.
| key | string | Cookie key |
| return | string | Corresponding cookie value |
set
Set cookie value.
| key | string | Cookie key |
| val | string | Cookie value |
| [options] | object | Cookie options |
| return | exports | Module cookie |
remove
Remove cookie value.
| key | string | Cookie key |
| [options] | object | Cookie options |
| return | exports | Module cookie |
copy
Copy text to clipboard using document.execCommand.
| text | string | Text to copy |
| [cb] | function | Optional callback |
createAssigner
Used to create extend, extendOwn and defaults.
| keysFn | function | Function to get object keys |
| defaults | boolean | No override when set to true |
| return | function | Result function, extend... |
createUrl
CreateObjectURL wrapper.
| data | File Blob string array | Url data |
| [opts] | object | Used when data is not a File or Blob |
| return | string | Blob url |
cssSupports
Check if browser supports a given CSS feature.
| name | string | Css property name |
| [val] | string | Css property value |
| return | boolean | True if supports |
curry
Function currying.
| fn | function | Function to curry |
| return | function | New curried function |
dateFormat
Simple but extremely useful date format function.
| [date=new Date] | Date | Date object to format |
| mask | string | Format mask |
| [utc=false] | boolean | UTC or not |
| [gmt=false] | boolean | GMT or not |
| 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 |
debounce
Return a new debounced version of the passed function.
| fn | function | Function to debounce |
| wait | number | Number of milliseconds to delay |
| return | function | New debounced function |
debug
A tiny JavaScript debugging utility.
| name | string | Namespace |
| return | function | Function to print decorated log |
decodeUriComponent
Better decodeURIComponent that does not throw if input is invalid.
| str | string | String to decode |
| return | string | Decoded string |
defaults
Fill in undefined properties in object with the first value present in the following list of defaults objects.
| obj | object | Destination object |
| *src | object | Sources objects |
| return | object | Destination object |
define
Define a module, should be used along with use.
| 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; }); 復制代碼defineProp
Shortcut for Object.defineProperty(defineProperties).
| obj | object | Object to define |
| prop | string | Property path |
| descriptor | object | Property descriptor |
| return | object | Object itself |
| obj | object | Object to define |
| prop | object | Property descriptors |
| return | object | Object itself |
delay
Invoke function after certain milliseconds.
| fn | function | Function to delay |
| wait | number | Number of milliseconds to delay invocation |
| [...args] | * | Arguments to invoke fn with |
delegate
Event delegation.
add
Add event delegation.
| el | element | Parent element |
| type | string | Event type |
| selector | string | Match selector |
| cb | function | Event callback |
remove
Remove event delegation.
var container = document.getElementById('container'); function clickHandler() {// Do something... } delegate.add(container, 'click', '.children', clickHandler); delegate.remove(container, 'click', '.children', clickHandler); 復制代碼detectBrowser
Detect browser info using ua.
| [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... } 復制代碼detectOs
Detect operating system using ua.
| [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... } 復制代碼difference
Create an array of unique array values not included in the other given array.
| arr | array | Array to inspect |
| [...rest] | array | Values to exclude |
| return | array | New array of filtered values |
dotCase
Convert string to "dotCase".
| str | string | String to convert |
| return | string | Dot cased string |
download
Trigger a file download on client side.
| data | Blob File string array | Data to download |
| name | string | File name |
| type=text/plain | string | Data type |
each
Iterate over elements of collection and invokes iteratee for each element.
| obj | object array | Collection to iterate over |
| iteratee | function | Function invoked per iteration |
| [ctx] | * | Function context |
easing
Easing functions adapted from http://jqueryui.com/
| percent | number | Number between 0 and 1 |
| return | number | Calculated number |
endWith
Check if string ends with the given target string.
| str | string | The string to search |
| suffix | string | String suffix |
| return | boolean | True if string ends with target |
escape
Escapes a string for insertion into HTML, replacing &, <, >, ", `, and ' characters.
| str | string | String to escape |
| return | string | Escaped string |
escapeJsStr
Escape string to be a valid JavaScript string literal between quotes.
http://www.ecma-international.org/ecma-262/5.1/#sec-7.8.4
| str | string | String to escape |
| return | string | Escaped string |
escapeRegExp
Escape special chars to be used as literals in RegExp constructors.
| str | string | String to escape |
| return | string | Escaped string |
evalCss
Load css into page.
| css | string | Css code |
evalJs
Execute js in given context.
| js | string | JavaScript code |
| [ctx=global] | object | Context |
every
Check if predicate return truthy for all elements.
| 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 |
extend
Copy all of the properties in the source objects over to the destination object.
| obj | object | Destination object |
| ...src | object | Sources objects |
| return | object | Destination object |
extendDeep
Recursive object extending.
| obj | object | Destination object |
| ...src | object | Sources objects |
| return | object | Destination object |
extendOwn
Like extend, but only copies own properties over to the destination object.
| obj | object | Destination object |
| *src | object | Sources objects |
| return | object | Destination object |
extractBlockCmts
Extract block comments from source code.
| str | string | String to extract |
| return | array | Block comments |
extractUrls
Extract urls from plain text.
| str | string | Text to extract |
| return | array | Url list |
fetch
Turn XMLHttpRequest into promise like.
Note: This is not a complete fetch pollyfill.
| url | string | Request url |
| options | object | Request options |
| return | promise | Request promise |
fibonacci
Calculate fibonacci number.
| n | number | Index of fibonacci sequence |
| return | number | Expected fibonacci number |
fileSize
Turn bytes into human readable file size.
| bytes | number | File bytes |
| return | string | Readable file size |
fill
Fill elements of array with value.
| 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 |
filter
Iterates over elements of collection, returning an array of all the values that pass a truth test.
| obj | array | Collection to iterate over |
| predicate | function | Function invoked per iteration |
| [ctx] | * | Predicate context |
| return | array | Array of all values that pass predicate |
find
Find the first value that passes a truth test in a collection.
| obj | array object | Collection to iterate over |
| predicate | function | Function invoked per iteration |
| [ctx] | * | Predicate context |
| return | * | First value that passes predicate |
findIdx
Return the first index where the predicate truth test passes.
| arr | array | Array to search |
| predicate | function | Function invoked per iteration |
| return | number | Index of matched element |
findKey
Return the first key where the predicate truth test passes.
| obj | object | Object to search |
| predicate | function | Function invoked per iteration |
| [ctx] | * | Predicate context |
| return | string | Key of matched element |
findLastIdx
Return the last index where the predicate truth test passes.
| arr | array | Array to search |
| predicate | function | Function invoked per iteration |
| return | number | Last index of matched element |
flatten
Recursively flatten an array.
| arr | array | Array to flatten |
| return | array | New flattened array |
fnParams
Get a function parameter's names.
| fn | function | Function to get parameters |
| return | array | Names |
format
Format string in a printf-like format.
| str | string | String to format |
| ...values | * | Values to replace format specifiers |
| return | string | Formatted string |
Format Specifiers
| %s | String |
| %d, %i | Integer |
| %f | Floating point value |
| %o | Object |
fraction
Convert number to fraction.
| num | number | Number to convert |
| return | string | Corresponding fraction |
freeze
Shortcut for Object.freeze.
Use Object.defineProperties if Object.freeze is not supported.
| obj | object | Object to freeze |
| return | object | Object passed in |
freezeDeep
Recursively use Object.freeze.
| obj | object | Object to freeze |
| return | object | Object passed in |
gcd
Compute the greatest common divisor using Euclid's algorithm.
| a | number | Number to calculate |
| b | number | Number to calculate |
| return | number | Greatest common divisor |
getUrlParam
Get url param.
| name | string | Param name |
| url=location | string | Url to get param |
| return | string | Param value |
has
Checks if key is a direct property.
| obj | object | Object to query |
| key | string | Path to check |
| return | boolean | True if key is a direct property |
hotkey
Capture keyboard input to trigger given events.
on
Register keyboard listener.
| key | string | Key string |
| listener | function | Key listener |
off
Unregister keyboard listener.
hotkey.on('k', function () {console.log('k is pressed'); }); function keyDown() {} hotkey.on('shift+a, shift+b', keyDown); hotkey.off('shift+a', keyDown); 復制代碼hslToRgb
Convert hsl to rgb.
| hsl | array | Hsl values |
| return | array | Rgb values |
identity
Return the first argument given.
| val | * | Any value |
| return | * | Given value |
idxOf
Get the index at which the first occurrence of value.
| arr | array | Array to search |
| val | * | Value to search for |
| fromIdx=0 | number | Index to search from |
indent
Indent each line in a string.
| str | string | String to indent |
| [char] | string | Character to prepend |
| [len] | number | Indent length |
| return | string | Indented string |
inherits
Inherit the prototype methods from one constructor into another.
| Class | function | Child Class |
| SuperClass | function | Super Class |
insertionSort
Insertion sort implementation.
| arr | array | Array to sort |
| [cmp] | function | Comparator |
intersect
Compute the list of values that are the intersection of all the arrays.
| ...arr | array | Arrays to inspect |
| return | array | New array of inspecting values |
intersectRange
Intersect two ranges.
| a | object | Range a |
| b | object | Range b |
| return | object | Intersection if exist |
invert
Create an object composed of the inverted keys and values of object.
| 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'} 復制代碼isAbsoluteUrl
Check if an url is absolute.
| url | string | Url to check |
| return | boolean | True if url is absolute |
isArgs
Check if value is classified as an arguments object.
| val | * | Value to check |
| return | boolean | True if value is an arguments object |
isArr
Check if value is an Array object.
| val | * | Value to check |
| return | boolean | True if value is an Array object |
isArrBuffer
Check if value is an ArrayBuffer.
| val | * | Value to check |
| return | boolean | True if value is an ArrayBuffer |
isArrLike
Check if value is array-like.
| 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 復制代碼isBlob
Check if value is a Blob.
| val | * | Value to check |
| return | boolean | True if value is a Blob |
isBool
Check if value is a boolean primitive.
| val | * | Value to check |
| return | boolean | True if value is a boolean |
isBrowser
Check if running in a browser.
console.log(isBrowser); // -> true if running in a browser 復制代碼isBuffer
Check if value is a buffer.
| val | * | The value to check |
| return | boolean | True if value is a buffer |
isClose
Check if values are close(almost equal) to each other.
abs(a-b) <= max(relTol * max(abs(a), abs(b)), absTol)
| 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 |
isDataUrl
Check if a string is a valid data url.
| str | string | String to check |
| return | boolean | True if string is a data url |
isDate
Check if value is classified as a Date object.
| val | * | value to check |
| return | boolean | True if value is a Date object |
isEl
Check if value is a DOM element.
| val | * | Value to check |
| return | boolean | True if value is a DOM element |
isEmail
Loosely validate an email address.
| val | string | Value to check |
| return | boolean | True if value is an email like string |
isEmpty
Check if value is an empty object or array.
| val | * | Value to check |
| return | boolean | True if value is empty |
isEqual
Performs an optimized deep comparison between the two objects, to determine if they should be considered equal.
| val | * | Value to compare |
| other | * | Other value to compare |
| return | boolean | True if values are equivalent |
isErr
Check if value is an error.
| val | * | Value to check |
| return | boolean | True if value is an error |
isEven
Check if number is even.
| num | number | Number to check |
| return | boolean | True if number is even |
isFile
Check if value is a file.
| val | * | Value to check |
| return | boolean | True if value is a file |
isFinite
Check if value is a finite primitive number.
| val | * | Value to check |
| return | boolean | True if value is a finite number |
isFn
Check if value is a function.
| 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 復制代碼isGeneratorFn
Check if value is a generator function.
| val | * | Value to check |
| return | boolean | True if value is a generator function |
isInt
Checks if value is classified as a Integer.
| val | * | Value to check |
| return | boolean | True if value is correctly classified |
isJson
Check if value is a valid JSON.
It uses JSON.parse() and a try... catch block.
| val | string | JSON string |
| return | boolean | True if value is a valid JSON |
isLeapYear
Check if a year is a leap year.
| year | number | Year to check |
| return | boolean | True if year is a leap year |
isMatch
Check if keys and values in src are contained in obj.
| obj | object | Object to inspect |
| src | object | Object of property values to match |
| return | boolean | True if object is match |
isMiniProgram
Check if running in wechat mini program.
console.log(isMiniProgram); // -> true if running in mini program. 復制代碼isMobile
Check whether client is using a mobile browser using ua.
| [ua=navigator.userAgent] | string | User agent |
| return | boolean | True if ua belongs to mobile browsers |
isNaN
Check if value is an NaN.
| 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 復制代碼isNative
Check if value is a native function.
| val | * | Value to check |
| return | boolean | True if value is a native function |
isNil
Check if value is null or undefined, the same as value == null.
| val | * | Value to check |
| return | boolean | True if value is null or undefined |
isNode
Check if running in node.
console.log(isNode); // -> true if running in node 復制代碼isNull
Check if value is an Null.
| val | * | Value to check |
| return | boolean | True if value is an Null |
isNum
Check if value is classified as a Number primitive or object.
| val | * | Value to check |
| return | boolean | True if value is correctly classified |
isNumeric
Check if value is numeric.
| val | * | Value to check |
| return | boolean | True if value is numeric |
isObj
Check if value is the language type of Object.
| val | * | Value to check |
| return | boolean | True if value is an object |
Language Spec
isObj({}); // -> true isObj([]); // -> true 復制代碼isOdd
Check if number is odd.
| num | number | Number to check |
| return | boolean | True if number is odd |
isPlainObj
Check if value is an object created by Object constructor.
| val | * | Value to check |
| return | boolean | True if value is a plain object |
isPrimitive
Check if value is string, number, boolean or null.
| val | * | Value to check |
| return | boolean | True if value is a primitive |
isPromise
Check if value looks like a promise.
| val | * | Value to check |
| return | boolean | True if value looks like a promise |
isRegExp
Check if value is a regular expression.
| val | * | Value to check |
| return | boolean | True if value is a regular expression |
isRelative
Check if path appears to be relative.
| path | string | Path to check |
| return | boolean | True if path appears to be relative |
isRetina
Determine if running on a high DPR device or not.
console.log(isRetina); // -> true if high DPR 復制代碼isStr
Check if value is a string primitive.
| val | * | Value to check |
| return | boolean | True if value is a string primitive |
isStream
Check if value is a Node.js stream.
| val | * | Value to check |
| return | boolean | True if value is a Node.js stream |
isTypedArr
Check if value is a typed array.
| val | * | Value to check |
| return | boolean | True if value is a typed array |
isUndef
Check if value is undefined.
| val | * | Value to check |
| return | boolean | True if value is undefined |
isUrl
Loosely validate an url.
| val | string | Value to check |
| return | boolean | True if value is an url like string |
isWindows
Check if platform is windows.
console.log(isWindows); // -> true if running on windows 復制代碼jsonp
A simple jsonp implementation.
| opts | object | Jsonp Options |
Available options:
| 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 |
kebabCase
Convert string to "kebabCase".
| str | string | String to convert |
| return | string | Kebab cased string |
keyCode
Key codes and key names conversion.
Get key code's name.
| code | number | Key code |
| return | string | Corresponding key name |
Get key name's code.
| name | string | Key name |
| return | number | Corresponding key code |
keys
Create an array of the own enumerable property names of object.
| obj | object | Object to query |
| return | array | Array of property names |
last
Get the last element of array.
| arr | array | The array to query |
| return | * | The last element of array |
lazyRequire
Require modules lazily.
var r = lazyRequire(require);var _ = r('underscore');// underscore is required only when _ is called. _().isNumber(5); 復制代碼linkify
Hyperlink urls in a string.
| str | string | String to hyperlink |
| [hyperlink] | function | Function to hyperlink url |
| return | string | Result string |
loadCss
Inject link tag into page with given href value.
| src | string | Style source |
| cb | function | Onload callback |
loadImg
Load image with given src.
| src | string | Image source |
| [cb] | function | Onload callback |
loadJs
Inject script tag into page with given src value.
| src | string | Script source |
| cb | function | Onload callback |
longest
Get the longest item in an array.
| arr | array | Array to inspect |
| return | * | Longest item |
lowerCase
Convert string to lower case.
| str | string | String to convert |
| return | string | Lower cased string |
lpad
Pad string on the left side if it's shorter than length.
| str | string | String to pad |
| len | number | Padding length |
| [chars] | string | String used as padding |
| return | string | Resulted string |
ltrim
Remove chars or white-spaces from beginning of string.
| str | string | String to trim |
| chars | string array | Characters to trim |
| return | string | Trimmed string |
map
Create an array of values by running each element in collection through iteratee.
| obj | array object | Collection to iterate over |
| iteratee | function | Function invoked per iteration |
| [ctx] | * | Function context |
| return | array | New mapped array |
mapObj
Map for objects.
| obj | object | Object to iterate over |
| iteratee | function | Function invoked per iteration |
| [ctx] | * | Function context |
| return | object | New mapped object |
matcher
Return a predicate function that checks if attrs are contained in an object.
| attrs | object | Object of property values to match |
| return | function | New predicate function |
max
Get maximum value of given numbers.
| ...num | number | Numbers to calculate |
| return | number | Maximum value |
memStorage
Memory-backed implementation of the Web Storage API.
A replacement for environments where localStorage or sessionStorage is not available.
var localStorage = window.localStorage || memStorage; localStorage.setItem('test', 'licia'); 復制代碼memoize
Memoize a given function by caching the computed result.
| fn | function | Function to have its output memoized |
| [hashFn] | function | Function to create cache key |
| return | function | New memoized function |
meta
Document meta manipulation, turn name and content into key value pairs.
Get meta content with given name. If name is omitted, all pairs will be return.
| [name] | string array | Meta name |
| return | string | Meta content |
Set meta content.
| name | string | Meta name |
| content | string | Meta content |
| metas | object | Object of name content pairs |
remove
Remove metas.
| name | string array | Meta name |
methods
Return a sorted list of the names of every method in an object.
| obj | object | Object to check |
| return | array | Function names in object |
min
Get minimum value of given numbers.
| ...num | number | Numbers to calculate |
| return | number | Minimum value |
mkdir
Recursively create directories.
| dir | string | Directory to create |
| [mode=0777] | number | Directory mode |
| callback | function | Callback |
moment
Tiny moment.js like implementation.
It only supports a subset of moment.js api.
Available methods
format, isValid, isLeapYear, isSame, isBefore, isAfter, year, month, date, hour, minute, second, millisecond, unix, clone, toDate, toArray, toJSON, toISOString, toObject, toString, set, startOf, endOf, add, subtract, diff
Not supported
locale and units like quarter and week.
Note: Format uses dateFormat module, so the mask is not quite the same as moment.js.
moment('20180501').format('yyyy-mm-dd'); // -> '2018-05-01' 復制代碼ms
Convert time string formats to milliseconds.
Turn time string into milliseconds.
| str | string | String format |
| return | number | Milliseconds |
Turn milliseconds into time string.
| num | number | Milliseconds |
| return | string | String format |
negate
Create a function that negates the result of the predicate function.
| predicate | function | Predicate to negate |
| return | function | New function |
nextTick
Next tick for both node and browser.
| cb | function | Function to call |
Use process.nextTick if available.
Otherwise setImmediate or setTimeout is used as fallback.
nextTick(function () {// Do something... }); 復制代碼noop
A no-operation function.
noop(); // Does nothing 復制代碼normalizePath
Normalize file path slashes.
| path | string | Path to normalize |
| return | string | Normalized path |
now
Gets the number of milliseconds that have elapsed since the Unix epoch.
now(); // -> 1468826678701 復制代碼objToStr
Alias of Object.prototype.toString.
| value | * | Source value |
| return | string | String representation of given value |
omit
Opposite of pick.
| obj | object | Source object |
| filter | string array function | Object filter |
| return | object | Filtered object |
optimizeCb
Used for function context binding.
orientation
Screen orientation helper.
on
Bind change event.
off
Unbind change event.
get
Get current orientation(landscape or portrait).
orientation.on('change', function (direction) {console.log(direction); // -> 'portrait' }); orientation.get(); // -> 'landscape' 復制代碼pad
Pad string on the left and right sides if it's shorter than length.
| str | string | String to pad |
| len | number | Padding length |
| chars | string | String used as padding |
| return | string | Resulted string |
pairs
Convert an object into a list of [key, value] pairs.
| obj | object | Object to convert |
| return | array | List of [key, value] pairs |
parallel
Run an array of functions in parallel.
| tasks | array | Array of functions |
| [cb] | function | Callback once completed |
parseArgs
Parse command line argument options, the same as minimist.
| args | array | Argument array |
| opts | object | Parse options |
| return | object | Parsed result |
options
| names | object | option names |
| shorthands | object | option shorthands |
partial
Partially apply a function by filling in given arguments.
| fn | function | Function to partially apply arguments to |
| ...partials | * | Arguments to be partially applied |
| return | function | New partially applied function |
pascalCase
Convert string to "pascalCase".
| str | string | String to convert |
| return | string | Pascal cased string |
perfNow
High resolution time up to microsecond precision.
var start = perfNow();// Do something.console.log(perfNow() - start); 復制代碼pick
Return a filtered copy of an object.
| obj | object | Source object |
| filter | string array function | Object filter |
| return | object | Filtered object |
pluck
Extract a list of property values.
| obj | object array | Collection to iterate over |
| key | string array | Property path |
| return | array | New array of specified property |
precision
Find decimal precision of a given number.
| num | number | Number to check |
| return | number | Precision |
prefix
Add vendor prefixes to a CSS attribute.
| name | string | Property name |
| return | string | Prefixed property name |
dash
Create a dasherize version.
prefix('text-emphasis'); // -> 'WebkitTextEmphasis' prefix.dash('text-emphasis'); // -> '-webkit-text-emphasis' prefix('color'); // -> 'color' 復制代碼promisify
Convert callback based functions into Promises.
| 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. }); 復制代碼property
Return a function that will itself return the key property of any passed-in object.
| path | string array | Path of the property to get |
| return | function | New accessor function |
query
Parse and stringify url query strings.
parse
Parse a query string into an object.
| str | string | Query string |
| return | object | Query object |
stringify
Stringify an object into a query string.
| obj | object | Query object |
| return | string | Query string |
raf
Shortcut for requestAnimationFrame.
Use setTimeout if native requestAnimationFrame is not supported.
var id = raf(function tick() {// Animation stuffraf(tick); }); raf.cancel(id); 復制代碼random
Produces a random number between min and max(inclusive).
| min | number | Minimum possible value |
| max | number | Maximum possible value |
| [floating=false] | boolean | Float or not |
| return | number | Random number |
randomBytes
Random bytes generator.
Use crypto module in node or crypto object in browser if possible.
| size | number | Number of bytes to generate |
| return | object | Random bytes of given length |
range
Create flexibly-numbered lists of integers.
| [start] | number | Start of the range |
| end | number | End of the range |
| step=1 | number | Value to increment or decrement by |
ready
Invoke callback when dom is ready, similar to jQuery ready.
| fn | function | Callback function |
reduce
Turn a list of values into a single value.
| obj | object array | Collection to iterate over |
| [iteratee=identity] | function | Function invoked per iteration |
| [initial] | * | Initial value |
| [ctx] | * | Function context |
| return | * | Accumulated value |
reduceRight
Right-associative version of reduce.
reduceRight([[1], [2], [3]], function (a, b) { return a.concat(b) }, []); // -> [3, 2, 1] 復制代碼reject
Opposite of filter.
| obj | array | Collection to iterate over |
| predicate | function | Function invoked per iteration |
| [ctx] | * | Predicate context |
| return | array | Array of all values that pass predicate |
remove
Remove all elements from array that predicate returns truthy for and return an array of the removed elements.
Unlike filter, this method mutates array.
| obj | array | Collection to iterate over |
| predicate | function | Function invoked per iteration |
| [ctx] | * | Predicate context |
| return | array | Array of all values that are removed |
repeat
Repeat string n-times.
| str | string | String to repeat |
| n | number | Repeat times |
| return | string | Repeated string |
restArgs
This accumulates the arguments passed into an array, after a given index.
| function | function | Function that needs rest parameters |
| startIndex | number | The start index to accumulates |
| return | function | Generated function with rest parameters |
rgbToHsl
Convert rgb to hsl.
| rgb | array | Rgb values |
| return | array | Hsl values |
rmCookie
Loop through all possible path and domain to remove cookie.
| key | string | Cookie key |
rmdir
Recursively remove directories.
| dir | string | Directory to remove |
| callback | function | Callback |
root
Root object reference, global in nodeJs, window in browser.
rpad
Pad string on the right side if it's shorter than length.
| str | string | String to pad |
| len | number | Padding length |
| chars | string | String used as padding |
| return | string | Resulted string |
rtrim
Remove chars or white-spaces from end of string.
| str | string | String to trim |
| chars | string array | Characters to trim |
| return | string | Trimmed string |
safeCb
Create callback based on input value.
safeDel
Delete object property.
| obj | object | Object to query |
| path | array string | Path of property to delete |
| return | * | Deleted value or undefined |
safeGet
Get object property, don't throw undefined error.
| obj | object | Object to query |
| path | array string | Path of property to get |
| return | * | Target value or undefined |
safeSet
Set value at path of object.
If a portion of path doesn't exist, it's created.
| obj | object | Object to modify |
| path | array string | Path of property to set |
| val | * | Value to set |
safeStorage
Use storage safely in safari private browsing and older browsers.
| [type='local'] | string | local or session |
| return | object | Specified storage |
sample
Sample random values from a collection.
| obj | array object | Collection to sample |
| n | number | Number of values |
| return | array | Array of sample values |
scrollTo
Scroll to a target with animation.
| target | element string number | Scroll target |
| options | object | Scroll options |
Options
| 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 |
selectionSort
Selection sort implementation.
| arr | array | Array to sort |
| [cmp] | function | Comparator |
shuffle
Randomize the order of the elements in a given array.
| arr | array | Array to randomize |
| return | array | Randomized Array |
size
Get size of object, length of array like object or the number of keys.
| obj | array object | Collection to inspect |
| return | number | Collection size |
slice
Create slice of source array or array-like object.
| array | array | Array to slice |
| [start=0] | number | Start position |
| [end=array.length] | number | End position, not included |
snakeCase
Convert string to "snakeCase".
| str | string | String to convert |
| return | string | Snake cased string |
some
Check if predicate return truthy for any element.
| 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 |
spaceCase
Convert string to "spaceCase".
| str | string | String to convert |
| return | string | Space cased string |
splitCase
Split different string case to an array.
| str | string | String to split |
| return | array | Result array |
splitPath
Split path into device, dir, name and ext.
| path | string | Path to split |
| return | object | Object containing dir, name and ext |
startWith
Check if string starts with the given target string.
| str | string | String to search |
| prefix | string | String prefix |
| return | boolean | True if string starts with prefix |
strHash
String hash function using djb2.
| str | string | String to hash |
| return | number | Hash result |
stringify
JSON stringify with support for circular object, function etc.
Undefined is treated as null value.
| obj | object | Object to stringify |
| spaces | number | Indent spaces |
| return | string | Stringified object |
stripAnsi
Strip ansi codes from a string.
| str | string | String to strip |
| return | string | Resulted string |
stripCmt
Strip comments from source code.
| str | string | Source code |
| return | string | Code without comments |
stripColor
Strip ansi color codes from a string.
| str | string | String to strip |
| return | string | Resulted string |
stripHtmlTag
Strip html tags from a string.
| str | string | String to strip |
| return | string | Resulted string |
sum
Compute sum of given numbers.
| ...num | number | Numbers to calculate |
| return | number | Sum of numbers |
template
Compile JavaScript template into function that can be evaluated for rendering.
| str | string | Template string |
| return | function | Compiled template function |
throttle
Return a new throttled version of the passed function.
| fn | function | Function to throttle |
| wait | number | Number of milliseconds to delay |
| return | function | New throttled function |
through
Tiny wrapper of stream Transform.
| [opts={}] | Object | Options to initialize stream |
| transform | function | Transform implementation |
| [flush] | function | Flush implementation |
obj
Shortcut for setting objectMode to true.
ctor
Return a class that extends stream Transform.
fs.createReadStream('in.txt').pipe(through(function (chunk, enc, cb){// Do something to chunkthis.push(chunk);cb();})).pipe(fs.createWriteStream('out.txt')); 復制代碼timeAgo
Format datetime with *** time ago statement.
| date | Date | Date to calculate |
| [now=new Date] | Date | Current date |
| return | string | Formatted time ago string |
timeTaken
Get execution time of a function.
| fn | function | Function to measure time |
| return | number | Execution time, ms |
toArr
Convert value to an array.
| val | * | Value to convert |
| return | array | Converted array |
toBool
Convert value to a boolean.
| val | * | Value to convert |
| return | boolean | Converted boolean |
toDate
Convert value to a Date.
| val | * | Value to convert |
| return | Date | Converted Date |
toEl
Convert html string to dom elements.
There should be only one root element.
| str | string | Html string |
| return | element | Html element |
toInt
Convert value to an integer.
| val | * | Value to convert |
| return | number | Converted integer |
toNum
Convert value to a number.
| val | * | Value to process |
| return | number | Resulted number |
toSrc
Convert function to its source code.
| fn | function | Function to convert |
| return | string | Source code |
toStr
Convert value to a string.
| val | * | Value to convert |
| return | string | Resulted string |
topoSort
Topological sorting algorithm.
| edges | array | Dependencies |
| return | array | Sorted order |
trigger
Trigger browser events.
| [el=document] | element | Element to trigger |
| type | string | Event type |
| opts | object | Options |
trim
Remove chars or white-spaces from beginning end of string.
| str | string | String to trim |
| chars | string array | Characters to trim |
| return | string | Trimmed string |
tryIt
Run function in a try catch.
| fn | function | Function to try catch |
| [cb] | function | Callback |
type
Determine the internal JavaScript [[Class]] of an object.
| val | * | Value to get type |
| return | string | Type of object, lowercased |
ucs2
UCS-2 encoding and decoding.
encode
Create a string using an array of code point values.
| arr | array | Array of code points |
| return | string | Encoded string |
decode
Create an array of code point values using a string.
| str | string | Input string |
| return | array | Array of code points |
unescape
Convert HTML entities back, the inverse of escape.
| str | string | String to unescape |
| return | string | unescaped string |
union
Create an array of unique values, in order, from all given arrays.
| ...arr | array | Arrays to inspect |
| return | array | New array of combined values |
uniqId
Generate a globally-unique id.
| prefix | string | Id prefix |
| return | string | Globally-unique id |
unique
Create duplicate-free version of an array.
| arr | array | Array to inspect |
| [compare] | function | Function for comparing values |
| return | array | New duplicate free array |
unzip
Opposite of zip.
| arr | array | Array of grouped elements to process |
| return | array | New array of regrouped elements |
upperCase
Convert string to upper case.
| str | string | String to convert |
| return | string | Uppercased string |
upperFirst
Convert the first character of string to upper case.
| str | string | String to convert |
| return | string | Converted string |
use
Use modules that is created by define.
| [requires] | array | Dependencies |
| method | function | Codes to be executed |
utf8
UTF-8 encoding and decoding.
encode
Turn any UTF-8 decoded string into UTF-8 encoded string.
| str | string | String to encode |
| return | string | Encoded string |
decode
| 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' 復制代碼uuid
RFC4122 version 4 compliant uuid generator.
Check RFC4122 4.4 for reference.
uuid(); // -> '53ce0497-6554-49e9-8d79-347406d2a88b' 復制代碼values
Create an array of the own enumerable property values of object.
| obj | object | Object to query |
| return | array | Array of property values |
viewportScale
Get viewport scale.
viewportScale(); // -> 3 復制代碼waterfall
Run an array of functions in series.
| tasks | array | Array of functions |
| [cb] | function | Callback once completed |
workerize
Move a stand-alone function to a worker thread.
| fn | function | Function to turn |
| return | function | Workerized Function |
wrap
Wrap the function inside a wrapper function, passing it as the first argument.
| fn | * | Function to wrap |
| wrapper | function | Wrapper function |
| return | function | New function |
zip
Merge together the values of each of the arrays with the values at the corresponding position.
| *arr | array | Arrays to process |
| return | array | New array of grouped elements |
轉載于:https://juejin.im/post/5af04752f265da0b873a6e6a
總結
以上是生活随笔為你收集整理的Licia:最全最实用的 JavaScript 工具库的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: url中携带中文乱码问题
- 下一篇: 使用php蓝天采集器抓取今日头条ajax