jQuery like style dom manipulator.
namespace $ {
class $ extends Select {
find(selector: string): $;
each(fn: types.AnyFn): $;
offset(): $offset.IOffset;
hide(): $;
show(): $;
first(): $;
last(): $;
get(index: number): Element;
eq(index: number): $;
on(event: string, selector: string, handler: types.AnyFn): $;
on(event: string, handler: types.AnyFn): $;
off(event: string, selector: string, handler: types.AnyFn): $;
off(event: string, handler: types.AnyFn): $;
html(): string;
html(value: string): $;
text(): string;
text(value: string): $;
val(): string;
val(value: string): $;
css(name: string): string;
css(name: string, value: string): $;
css(properties: types.PlainObj<string | number>): $;
attr(name: string): string;
attr(name: string, value: string): $;
attr(attributes: types.PlainObj<string>): $;
data(name: string): string;
data(name: string, value: string): $;
data(attributes: types.PlainObj<string>): $;
rmAttr(name: string): $;
remove(): $;
addClass(name: string | string[]): $;
rmClass(name: string): $;
toggleClass(name: string): $;
hasClass(name: string): boolean;
parent(): $;
append(content: string | Element): $;
prepend(content: string | Element): $;
before(content: string | Element): $;
after(content: string | Element): $;
}
}
declare function $(selector: string | Element | Document): $.$;
offset, hide, show, first, last, get, eq, on, off, html, text, val, css, attr, data, rmAttr, remove, addClass, rmClass, toggleClass, hasClass, append, prepend, before, after
const $btn = $('#btn');
$btn.html('eustia');
$btn.addClass('btn');
$btn.show();
$btn.on('click', function() {
// Do something...
});
Element attribute manipulation.
namespace $attr {
function remove(element: $safeEls.El, name: string): void;
}
function $attr(
element: $safeEls.El,
name: string,
value: string
): void;
function $attr(
element: $safeEls.El,
attributes: types.PlainObj<string>
): void;
function $attr(element: $safeEls.El, name: string): string;
Get the value of an attribute for the first element in the set of matched elements.
Name | Desc |
---|---|
element | Elements to manipulate |
name | Attribute name |
return | Attribute value of first element |
Set one or more attributes for the set of matched elements.
Name | Desc |
---|---|
element | Elements to manipulate |
name | Attribute name |
val | Attribute value |
Name | Desc |
---|---|
element | Elements to manipulate |
attributes | Object of attribute-value pairs to set |
Remove an attribute from each element in the set of matched elements.
Name | Desc |
---|---|
element | Elements to manipulate |
name | Attribute name |
$attr('#test', 'attr1', 'test');
$attr('#test', 'attr1'); // -> test
$attr.remove('#test', 'attr1');
$attr('#test', {
attr1: 'test',
attr2: 'test'
});
Element class manipulations.
const $class: {
add(element: $safeEls.El, name: string | string[]): void;
has(element: $safeEls.El, name: string): boolean;
toggle(element: $safeEls.El, name: string): void;
remove(element: $safeEls.El, name: string): void;
};
Add the specified class(es) to each element in the set of matched elements.
Name | Desc |
---|---|
element | Elements to manipulate |
names | Classes to add |
Determine whether any of the matched elements are assigned the given class.
Name | Desc |
---|---|
element | Elements to manipulate |
name | Class name |
return | 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 | Desc |
---|---|
element | Elements to manipulate |
name | Class name to toggle |
Remove a single class, multiple classes, or all classes from each element in the set of matched elements.
Name | Desc |
---|---|
element | Elements to manipulate |
name | 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.
function $css(element: $safeEls.El, name: string): string;
function $css(
element: $safeEls.El,
name: string,
val: string
): void;
function $css(
element: $safeEls.El,
properties: types.PlainObj<string | number>
): void;
Get the computed style properties for the first element in the set of matched elements.
Name | Desc |
---|---|
element | Elements to manipulate |
name | Property name |
return | Css value of first element |
Set one or more CSS properties for the set of matched elements.
Name | Desc |
---|---|
element | Elements to manipulate |
name | Property name |
val | Css value |
Name | Desc |
---|---|
element | Elements to manipulate |
properties | Object of css-value pairs to set |
$css('#test', {
color: '#fff',
background: 'black',
opacity: 0.5
});
$css('#test', 'display', 'block');
$css('#test', 'color'); // -> #fff
Wrapper of $attr, adds data- prefix to keys.
function $data(
element: $safeEls.El,
name: string,
value: string
): void;
function $data(
element: $safeEls.El,
attributes: types.PlainObj<string>
): void;
function $data(element: $safeEls.El, name: string): string;
$data('#test', 'attr1', 'eustia');
bind events to certain dom elements.
const $event: {
on(
element: $safeEls.El,
event: string,
selector: string,
handler: types.AnyFn
): void;
on(element: $safeEls.El, event: string, handler: types.AnyFn): void;
off(
element: $safeEls.El,
event: string,
selector: string,
handler: types.AnyFn
): void;
off(element: $safeEls.El, event: string, handler: types.AnyFn): void;
};
function clickHandler() {
// Do something...
}
$event.on('#test', 'click', clickHandler);
$event.off('#test', 'click', clickHandler);
Insert html on different position.
namespace $insert {
type IInsert = (element: $safeEls.El, content: string | Element) => void;
}
const $insert: {
before: $insert.IInsert;
after: $insert.IInsert;
append: $insert.IInsert;
prepend: $insert.IInsert;
};
Insert content before elements.
Insert content after elements.
Insert content to the beginning of elements.
Insert content to the end of elements.
Name | Desc |
---|---|
element | Elements to manipulate |
content | Html strings or element |
// <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.
namespace $offset {
interface IOffset {
left: number;
top: number;
width: number;
height: number;
}
}
function $offset(element: $safeEls.El): $offset.IOffset;
Name | Desc |
---|---|
element | Elements to get offset |
return | Element position |
$offset('#test'); // -> {left: 0, top: 0, width: 0, height: 0}
Element property html, text, val getter and setter.
namespace $property {
interface IProperty {
(element: $safeEls.El, value: string): void;
(element: $safeEls.El): string;
}
}
const $property: {
html: $property.IProperty;
val: $property.IProperty;
text: $property.IProperty;
};
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.
function $remove(element: $safeEls.El);
Name | Desc |
---|---|
element | Elements to delete |
$remove('#test');
Convert value into an array, if it's a string, do querySelector.
namespace $safeEls {
type El = Element | Element[] | NodeListOf<Element> | string;
}
function $safeEls(val: $safeEls.El): Element[];
Name | Desc |
---|---|
val | Value to convert |
return | Array of elements |
$safeEls(document.querySelector('.test'));
$safeEls(document.querySelectorAll('.test'));
$safeEls('.test'); // -> Array of elements with test class
Show elements.
function $show(element: $safeEls.El): void;
Name | Desc |
---|---|
element | Elements to show |
$show('#test');
JavaScript Benchmark.
namespace Benchmark {
interface IOptions {
minTime?: number;
maxTime?: number;
minSamples?: number;
delay?: number;
name?: string;
}
interface IResult {
name: string;
mean: number;
variance: number;
deviation: number;
sem: number;
moe: number;
rme: number;
hz: number;
sample: number[];
}
}
class Benchmark {
constructor(fn: types.AnyFn, options?: Benchmark.IOptions);
run(): Promise<Benchmark.IResult>;
static all(
benches: Array<types.AnyFn | Benchmark>,
options?: Benchmark.IOptions
): Promise<Benchmark.IResult[]>;
}
Name | Desc |
---|---|
fn | Code for speed testing |
options | Benchmark options |
Available options:
Name | Desc |
---|---|
minTime=50 | Time needed to reduce uncertainty |
maxTime=5000 | Maximum time for running benchmark |
minSamples=5 | Minimum sample size |
delay=5 | Delay between test cycles |
name | Benchmark name |
Run benchmark, returns a promise.
[static] Run some benchmarks.
const benchmark = new Benchmark(
function test() {
!!'Hello World!'.match(/o/);
},
{
maxTime: 1500
}
);
benchmark.run().then(result => {
console.log(String(result));
});
Benchmark.all([
function regExp() {
/o/.test('Hello World!');
},
function indexOf() {
'Hello World!'.indexOf('o') > -1;
},
function match() {
!!'Hello World!'.match(/o/);
}
]).then(results => {
console.log(String(results));
});
Use Blob when available, otherwise BlobBuilder.
Name | Desc |
---|---|
parts | Blob parts |
options | Options |
const blob = new Blob([]);
Bloom filter implementation.
class BloomFilter {
constructor(size?: number, k?: number);
add(val: string): void;
test(val: string): boolean;
}
Name | Desc |
---|---|
size=1024 | Number of buckets |
k=3 | Number of Hash functions |
Add an element to the filter.
Name | Desc |
---|---|
val | Value to add |
Test if an element is in the filter.
Name | Desc |
---|---|
val | Value to test |
return | True if probably, false if definitely not |
const bloom = new BloomFilter(256, 3);
bloom.add('Bruce Wayne');
bloom.add('Clark Kent');
bloom.test('Clark Kent'); // -> true
bloom.test('Bruce Wayne'); // -> true
bloom.test('Tony Stark'); // -> false
Modify object props without caring about letter case.
class Caseless {
constructor(obj: any);
getKey(key: string): string | void;
set(key: string, val: any): void;
get(key: string): any;
remove(key: string): void;
has(key: string): boolean;
}
Name | Desc |
---|---|
obj | Target object |
Get key with preserved casing.
Name | Desc |
---|---|
key | Caseless key |
return | Object key |
Set value.
Name | Desc |
---|---|
key | Caseless key |
val | Value to set |
Get value.
Name | Desc |
---|---|
key | Caseless key |
return | Value of given key |
Remove value.
Name | Desc |
---|---|
key | Caseless key |
Determine whether target object has given key.
Name | Desc |
---|---|
key | Caseless key |
return | True if has given key |
const headers = { 'Content-Type': 'text/javascript' };
const c = new Caseless(headers);
c.set('content-type', 'text/css');
console.log(headers); // -> { 'Content-Type': 'text/css' }
c.getKey('content-type'); // -> 'Content-Type'
c.remove('content-type');
c.has('content-type'); // -> false
Create JavaScript class.
namespace Class {
class Base {
toString(): string;
}
class IConstructor extends Base {
constructor(...args: any[]);
static extend(methods: any, statics: any): IConstructor;
static inherits(Class: types.AnyFn): void;
static methods(methods: any): IConstructor;
static statics(statics: any): IConstructor;
[method: string]: any;
}
}
function Class(methods: any, statics?: any): Class.IConstructor;
Name | Desc |
---|---|
methods | Public methods |
[statics|Static methods | |return |Function used to create instances|
const People = Class({
initialize: function People(name, age) {
this.name = name;
this.age = age;
},
introduce: function() {
return 'I am ' + this.name + ', ' + this.age + ' years old.';
}
});
const Student = People.extend(
{
initialize: function Student(name, age, school) {
this.callSuper(People, 'initialize', arguments);
this.school = school;
},
introduce: function() {
return (
this.callSuper(People, 'introduce') +
'\n I study at ' +
this.school +
'.'
);
}
},
{
is: function(obj) {
return obj instanceof Student;
}
}
);
const a = new Student('allen', 17, 'Hogwarts');
a.introduce(); // -> 'I am allen, 17 years old. \n I study at Hogwarts.'
Student.is(a); // -> true
Color converter.
namespace Color {
interface IColor {
val: number[];
model: string;
}
}
class Color {
constructor(color: string | Color.IColor);
toRgb(): string;
toHex(): string;
toHsl(): string;
static parse(colorStr: string): Color.IColor;
}
Name | Desc |
---|---|
color | 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 | Desc |
---|---|
color | Color string |
return | Object containing value and model |
Color.parse('rgb(170, 287, 204, 0.5)'); // -> {val: [170, 187, 204, 0.5], model: 'rgb'}
const color = new Color('#abc');
color.toRgb(); // -> 'rgb(170, 187, 204)'
color.toHsl(); // -> 'hsl(210, 25%, 73%)'
Object delegation.
class Delegator {
constructor(host: object, target: object | string);
method(name: string, target?: string): Delegator;
getter(name: string, target?: string): Delegator;
setter(name: string, target?: string): Delegator;
access(name: string, target?: string): Delegator;
}
Name | Desc |
---|---|
host | Host object |
target | Delegation target |
Allow method to be accessed on the host object.
Name | Desc |
---|---|
name | Host method name |
target=name | Target method name |
Create a getter.
Create a setter.
Create a accessor, same as calling both setter and getter.
const host = {
target: {
a() {
return 'a';
},
b: 'b',
c: 'c',
d: 'd',
e() {
return 'e';
}
}
};
const delegator = new Delegator(host, 'target');
delegator
.method('a')
.getter('b')
.setter('c')
.access('d');
host.a(); // -> 'a'
host.b; // -> 'b'
host.c = 5;
host.target.c; // -> 5
host.d; // -> 'd'
host.d = 5;
host.d; // -> 5
Flux dispatcher.
class Dispatcher {
dispatch(payload: any);
register(cb: types.AnyFn): void;
waitFor(ids: string[]): void;
unregister(id: string): void;
isDispatching(): boolean;
}
const dispatcher = new Dispatcher();
dispatcher.register(function(payload) {
switch (
payload.actionType
// Do something
) {
}
});
dispatcher.dispatch({
actionType: 'action'
});
Event emitter class which provides observer pattern.
class Emitter {
on(event: string, listener: types.AnyFn): Emitter;
off(event: string, listener: types.AnyFn): Emitter;
once(event: string, listener: types.AnyFn): Emitter;
emit(event: string, ...args: any[]): Emitter;
removeAllListeners(event?: string): Emitter;
static mixin(obj: any): any;
}
Bind event.
Unbind event.
Bind event that trigger once.
Name | Desc |
---|---|
event | Event name |
listener | Event listener |
Emit event.
Name | Desc |
---|---|
event | Event name |
...args | Arguments passed to listener |
Remove all listeners.
Name | Desc |
---|---|
event | Event name |
[static] Mixin object class methods.
Name | Desc |
---|---|
obj | Object to mixin |
const event = new Emitter();
event.on('test', function(name) {
console.log(name);
});
event.emit('test', 'licia'); // Logs out 'licia'.
Emitter.mixin({});
Enum type implementation.
class Enum {
size: number;
constructor(map: string[] | { [member: string]: any });
[key: string]: any;
}
Name | Desc |
---|---|
arr | Array of strings |
Name | Desc |
---|---|
obj | Pairs of key and value |
const importance = new Enum([
'NONE',
'TRIVIAL',
'REGULAR',
'IMPORTANT',
'CRITICAL'
]);
const val = 1;
if (val === importance.CRITICAL) {
// Do something.
}
Binary file storage.
class FileBlobStore extends Emitter {
constructor(path: string, data?: types.PlainObj<Buffer>);
set(key: string, buf: Buffer): void;
set(values: types.PlainObj<Buffer>): void;
get(key: string): Buffer | void;
get(keys: string[]): types.PlainObj<Buffer>;
remove(key: string): void;
remove(keys: string[]): void;
clear(): void;
each(fn: (val: Buffer, key: string) => void): void;
save(): void;
}
Most api is the same as Store module, except only buffer is accepted.
Save data to disk.
const store = new FileBlobStore('path/to/file');
store.set('name', Buffer.from('licia'));
process.on('exit', () => store.save());
File storage.
class FileStore extends Store {
constructor(path: string, data?: any);
}
Name | Desc |
---|---|
path | File path to store |
data | Default data |
const store = new FileStore('path/to/file');
store.set('name', 'licia');
Hash table implementation.
class HashTable {
constructor(size?: number);
set(key: string, val: any): void;
get(key: string): any;
has(key: string): boolean;
delete(key: string): void;
}
Name | Desc |
---|---|
size=32 | Bucket size |
Set value.
Name | Desc |
---|---|
key | Value key |
val | Value to set |
Get value.
Name | Desc |
---|---|
key | Value key |
return | Value of given key |
Check if has value.
Name | Desc |
---|---|
key | Value key |
return | True if value exists |
Delete value.
const hashTable = new HashTable(128);
hashTable.set('name', 'redhoodsu');
hashTable.get('name'); // -> 'redhoodsu'
hashTable.has('name'); // -> true
hashTable.delete('name');
hashTable.has('name'); // -> false
Heap implementation.
class Heap {
size: number;
constructor(cmp?: types.AnyFn);
clear(): void;
add(item: any): number;
poll(): any;
peek(): any;
}
Heap size.
Name | Desc |
---|---|
cmp | Comparator |
Clear the heap.
Add an item to the heap.
Name | Desc |
---|---|
item | Item to add |
return | Current size |
Retrieve and remove the root item of the heap.
Same as poll, but does not remove the item.
const heap = new Heap(function(a, b) {
return b - a;
});
heap.add(2);
heap.add(1);
heap.add(4);
heap.add(5);
heap.poll(); // -> 5
console.log(heap.size); // -> 4
V8 heap snapshot manipulator.
class HeapSnapshot {
nodes: LinkedList;
edges: LinkedList;
constructor(profile: any);
}
Name | Desc |
---|---|
profile | Profile to parse |
Parsed nodes.
Parsed edges.
const fs = require('fs');
const data = fs.readFileSync('path/to/heapsnapshot', 'utf8');
const heapSnapshot = new HeapSnapshot(data);
let totalSize = 0;
heapSnapshot.nodes.forEach(node => (totalSize += node.selfSize));
console.log(totalSize);
Simple internationalization library.
class I18n {
constructor(locale: string, langs: types.PlainObj<any>);
set(locale: string, lang: types.PlainObj<any>): void;
t(path: string | string[], data?: types.PlainObj<any>): string;
locale(locale: string): void;
}
Name | Desc |
---|---|
locale | Locale code |
langs | Language data |
Add language or append extra keys to existing language.
Name | Desc |
---|---|
locale | Locale code |
lang | Language data |
Set default locale.
Name | Desc |
---|---|
locale | Locale code |
Get translation text.
Name | Desc |
---|---|
path | Path of translation to get |
data | Data to pass in |
return | Translation text |
const i18n = new I18n('en', {
en: {
welcome: 'Hello, {{name}}!',
curTime(data) {
return 'Current time is ' + data.time;
}
},
cn: {
welcome: '你好,{{name}}!'
}
});
i18n.set('cn', {
curTime(data) {
return '当前时间是 ' + data.time;
}
});
i18n.t('welcome', { name: 'licia' }); // -> 'Hello, licia!'
i18n.locale('cn');
i18n.t('curTime', { time: '5:47 pm' }); // -> '当前时间是 5:47 pm'
Json to json transformer.
class JsonTransformer {
constructor(data: any);
set(key: string, val: any): JsonTransformer;
get(key?: string): any;
map(from: string, to: string, fn: types.AnyFn): JsonTransformer;
map(from: string, fn: types.AnyFn): JsonTransformer;
filter(from: string, to: string, fn: types.AnyFn): JsonTransformer;
filter(from: string, fn: types.AnyFn): JsonTransformer;
remove(keys: string | string[]): JsonTransformer;
compute(
from: string | string[],
to: string,
fn: types.AnyFn
): JsonTransformer;
compute(from: string, fn: types.AnyFn): JsonTransformer;
toString(): string;
}
Name | Desc |
---|---|
data={} | Json object to manipulate |
Set object value.
Name | Desc |
---|---|
key | Object key |
val | Value to set |
If key is not given, the whole source object is replaced by val.
Get object value.
Name | Desc |
---|---|
key | Object key |
return | Specified value or whole object |
Remove object value.
Name | Desc |
---|---|
key | Object keys to remove |
Shortcut for array map.
Name | Desc |
---|---|
from | From object path |
to | Target object path |
fn | Function invoked per iteration |
Shortcut for array filter.
Compute value from several object values.
Name | Desc |
---|---|
from | Source values |
to | Target object path |
fn | Function to compute target value |
const data = new JsonTransformer({
books: [
{
title: 'Book 1',
price: 5
},
{
title: 'Book 2',
price: 10
}
],
author: {
lastname: 'Su',
firstname: 'RedHood'
}
});
data.filter('books', function(book) {
return book.price > 5;
});
data.compute('author', function(author) {
return author.firstname + author.lastname;
});
data.set('count', data.get('books').length);
data.get(); // -> {books: [{title: 'Book 2', price: 10}], author: 'RedHoodSu', count: 1}
Doubly-linked list implementation.
namespace LinkedList {
class Node {
value: any;
prev: Node | null;
next: Node | null;
}
}
class LinkedList {
size: number;
head: LinkedList.Node;
tail: LinkedList.Node;
push(val: any): number;
pop(): any;
unshift(val: any): number;
shift(): any;
find(fn: types.AnyFn): LinkedList.Node | void;
delNode(node: LinkedList.Node): void;
forEach(iterator: types.AnyFn, ctx?: any);
toArr(): any[];
}
List size.
First node.
Last node.
Add an value to the end of the list.
Name | Desc |
---|---|
val | Value to push |
return | 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.
Remove node.
Find node.
Name | Desc |
---|---|
fn | Function invoked per iteration |
return | First value that passes predicate |
Iterate over the list.
Convert the list to a JavaScript array.
const linkedList = new LinkedList();
linkedList.push(5);
linkedList.pop(); // -> 5
LocalStorage wrapper.
class LocalStore extends Store {
constructor(name: string, data?: {});
}
Extend from Store.
Name | Desc |
---|---|
name | LocalStorage item name |
data | Default data |
const store = new LocalStore('licia');
store.set('name', 'licia');
Simple logger with level filter.
class Logger extends Emitter {
name: string;
formatter(type: string, argList: any[]): any[];
constructor(name: string, level?: string | number);
setLevel(level: string | number): Logger;
getLevel(): number;
trace(...args: any[]): Logger;
debug(...args: any[]): Logger;
info(...args: any[]): Logger;
warn(...args: any[]): Logger;
error(...args: any[]): Logger;
static level: Enum;
}
Name | Desc |
---|---|
name | Logger name |
level=DEBUG | Logger level |
Set level.
Name | Desc |
---|---|
level | Logger level |
Get current level.
Logging methods.
TRACE, DEBUG, INFO, WARN, ERROR and SILENT.
const logger = new Logger('licia', Logger.level.ERROR);
logger.trace('test');
// Format output.
logger.formatter = function(type, argList) {
argList.push(new Date().getTime());
return argList;
};
logger.on('all', function(type, argList) {
// It's not affected by log level.
});
logger.on('debug', function(argList) {
// Affected by log level.
});
Simple LRU cache.
class Lru {
constructor(max: number);
has(key: string): boolean;
remove(key: string): void;
get(key: string): any;
set(key: string, val: any): void;
clear(): void;
}
Name | Desc |
---|---|
max | Max items in cache |
Check if has cache.
Name | Desc |
---|---|
key | Cache key |
return | True if value exists |
Remove cache.
Name | Desc |
---|---|
key | Cache key |
Get cache value.
Name | Desc |
---|---|
key | Cache key |
return | Cache value |
Set cache.
Name | Desc |
---|---|
key | Cache key |
val | Cache value |
Clear cache.
const cache = new Lru(50);
cache.set('test', 'licia');
cache.get('test'); // -> 'licia'
CSS media query listener.
class MediaQuery extends Emitter {
constructor(query: string);
setQuery(query: string): void;
isMatch(): boolean;
}
Extend from Emitter.
Name | Desc |
---|---|
query | Media query |
Update query.
Return true if given media query matches.
Triggered when a media query matches.
Opposite of match.
const mediaQuery = new MediaQuery('screen and (max-width:1000px)');
mediaQuery.isMatch(); // -> false
mediaQuery.on('match', () => {
// Do something...
});
Safe MutationObserver, does nothing if MutationObserver is not supported.
const observer = new MutationObserver(function(mutations) {
// Do something.
});
observer.observe(document.documentElement);
observer.disconnect();
Priority queue implementation.
class PriorityQueue {
size: number;
constructor(cmp?: types.AnyFn);
clear(): void;
enqueue(item: any): number;
dequeue(): any;
peek(): any;
}
Queue size.
Name | Desc |
---|---|
cmp | Comparator |
Clear the queue.
Add an item to the queue.
Name | Desc |
---|---|
item | Item to add |
return | Current size |
Retrieve and remove the highest priority item of the queue.
Same as dequeue, but does not remove the item.
const queue = new PriorityQueue(function(a, b) {
if (a.priority > b.priority) return 1;
if (a.priority === b.priority) return -1;
return 0;
});
queue.enqueue({
priority: 1000,
value: 'apple'
});
queue.enqueue({
priority: 500,
value: 'orange'
});
queue.dequeue(); // -> { priority: 1000, value: 'apple' }
Lightweight Promise implementation.
function get(url) {
return new Promise(function(resolve, reject) {
const req = new XMLHttpRequest();
req.open('GET', url);
req.onload = function() {
req.status == 200
? resolve(req.response)
: reject(Error(req.statusText));
};
req.onerror = function() {
reject(Error('Network Error'));
};
req.send();
});
}
get('test.json').then(function(result) {
// Do something...
});
Like es6 Map, without iterators.
const PseudoMap: typeof Map;
It supports only string keys, and uses Map if exists.
const map = new PseudoMap();
map.set('1', 1);
map.get('1'); // -> 1
Queue data structure.
class Queue {
size: number;
clear(): void;
enqueue(item: any): number;
dequeue(): any;
peek(): any;
forEach(iterator: types.AnyFn, context?: any): void;
toArr(): any[];
}
Queue size.
Clear the queue.
Add an item to the queue.
Name | Desc |
---|---|
item | Item to enqueue |
return | Current size |
Remove the first item of the queue.
Get the first item without removing it.
Iterate over the queue.
Name | Desc |
---|---|
iterator | Function invoked iteration |
ctx | Function context |
Convert queue to a JavaScript array.
const queue = new Queue();
console.log(queue.size); // -> 0
queue.enqueue(2);
queue.enqueue(3);
queue.dequeue(); // -> 2
console.log(queue.size); // -> 1
queue.peek(); // -> 3
console.log(queue.size); // -> 1
LRU implementation without linked list.
class QuickLru {
constructor(max: number);
has(key: string): boolean;
remove(key: string): void;
get(key: string): any;
set(key: string, val: any): void;
clear(): void;
}
Inspired by the hashlru algorithm.
The api is the same as Lru module.
const cache = new QuickLru(50);
cache.set('test', 'licia');
cache.get('test'); // -> 'licia'
Readiness manager.
class Readiness {
signal(tasks: string | string[]): void;
isReady(tasks: string | string[]): boolean;
ready(tasks: string | string[], fn?: types.AnyFn): Promise<void>;
}
Signal task is ready.
Name | Desc |
---|---|
tasks | Ready tasks |
Register ready callback.
Name | Desc |
---|---|
tasks | Tasks to listen |
fn | Callback to trigger if tasks are ready |
return | Promise that will be resolved when ready |
Check if tasks are ready.
Name | Desc |
---|---|
tasks | Tasks to check |
return | True if all tasks are ready |
const readiness = new Readiness();
readiness.ready('serverCreated', function() {
// Do something.
});
readiness.signal('serverCreated');
readiness.isReady('serverCreated'); // -> true
Simplified redux like state container.
class ReduceStore {
constructor(reducer: types.AnyFn, initialState: any);
subscribe(listener: types.AnyFn): types.AnyFn;
dispatch(action: any): any;
getState(): any;
}
Name | Desc |
---|---|
reducer | Function returns next state |
initialState | Initial state |
Add a change listener.
Name | Desc |
---|---|
listener | Callback to invoke on every dispatch |
return | Function to unsubscribe |
Dispatch an action.
Name | Desc |
---|---|
action | Object representing changes |
return | Same action object |
Get the current state.
const store = new ReduceStore(function(state, action) {
switch (action.type) {
case 'INCREMENT':
return state + 1;
case 'DECREMENT':
return state - 1;
default:
return state;
}
}, 0);
store.subscribe(function() {
console.log(store.getState());
});
store.dispatch({ type: 'INCREMENT' }); // 1
store.dispatch({ type: 'INCREMENT' }); // 2
store.dispatch({ type: 'DECREMENT' }); // 1
Detect if element's size has changed.
class ResizeSensor extends SingleEmitter {
constructor(el: HTMLElement);
destroy(): void;
}
Name | Desc |
---|---|
element | Element to monitor size |
Stop monitoring resize event.
const target = document.getElementById('test');
const sensor = new ResizeSensor(target);
sensor.addListener(function() {
// Trigger if element's size changed.
});
Simple wrapper of querySelectorAll to make dom selection easier.
class Select {
constructor(selector: string | Element | Document);
find(selector: string): Select;
each(fn: types.AnyFn): Select;
}
Name | Desc |
---|---|
selector | Dom selector string |
Get desdendants of current matched elements.
Name | Desc |
---|---|
selector | Dom selector string |
Iterate over matched elements.
Name | Desc |
---|---|
fn | Function to execute for each element |
const $test = new Select('#test');
$test.find('.test').each(function(idx, element) {
// Manipulate dom nodes
});
Limit simultaneous access to a resource.
class Semaphore {
constructor(counter?: number);
wait(fn: () => void): void;
signal(): void;
}
Name | Desc |
---|---|
counter=1 | Initial counter |
Wait to execute until counter is bigger than 0.
Name | Desc |
---|---|
fn | Function to execute |
Wake up one waiter if any.
const sem = new Semaphore(10);
require('http')
.createServer((req, res) => {
sem.wait(function() {
res.end('.');
setTimeout(() => sem.signal(), 500);
});
})
.listen(3000);
SessionStorage wrapper.
class SessionStore extends Store {
constructor(name: string, data?: any);
}
Extend from Store.
Name | Desc |
---|---|
name | SessionStorage item name |
data | Default data |
const store = new SessionStore('licia');
store.set('name', 'licia');
Event emitter with single event type.
class SingleEmitter {
addListener(listener: types.AnyFn): void;
rmListener(listener: types.AnyFn): void;
emit(...args: any[]): void;
rmAllListeners(): void;
static mixin(obj: any): void;
}
Add listener.
Remove listener.
Name | Desc |
---|---|
listener | Event listener |
Remove all listeners.
Call listeners.
Name | Desc |
---|---|
...args | Arguments passed to listener |
[static] Mixin object class methods.
Name | Desc |
---|---|
obj | Object to mixin |
const event = new SingleEmitter();
event.addListener(function(name) {
console.log(name);
});
event.emit('licia'); // Logs out 'licia'.
Tiny WebSocket wrapper.
class Socket extends Emitter {
constructor(
url: string,
options?: {
protocols?: string | string[];
reconnect?: boolean;
}
);
send(message: any): void;
close(code?: number, reason?: string): void;
connect(): void;
}
Extend from Emitter.
Name | Desc |
---|---|
url | Url to connect |
options | Connect options |
Available options:
Name | Desc |
---|---|
protocols | Protocol string |
reconnect=true | Try to reconnect if possible |
Send message.
Name | Desc |
---|---|
message | Message to send |
Close WebSocket.
Name | Desc |
---|---|
code | Status code |
reason | Reason of closing |
Connect WebSocket, called when initialized.
const ws = new Socket('ws://localhost:8001');
ws.on('open', e => ws.send('Hello'));
Stack data structure.
class Stack {
size: number;
clear(): void;
push(item: any): number;
pop(): any;
peek(): any;
forEach(iterator: types.AnyFn, context?: any): void;
toArr(): any[];
}
Stack size.
Clear the stack.
Add an item to the stack.
Name | Desc |
---|---|
item | Item to add |
return | Current size |
Get the last item of the stack.
Get the last item without removing it.
Iterate over the stack.
Name | Desc |
---|---|
iterator | Function invoked iteration |
ctx | Function context |
Convert the stack to a JavaScript array.
const stack = new Stack();
stack.push(2); // -> 1
stack.push(3); // -> 2
stack.pop(); // -> 3
Simple state machine.
class State extends Emitter {
constructor(initial: string, events: any);
is(state: string): boolean;
[event: string]: any;
}
Extend from Emitter.
Name | Desc |
---|---|
initial | Initial state |
events | Events to change state |
Check current state.
Name | Desc |
---|---|
state | State to check |
return | True if current state equals given value |
const state = new State('empty', {
load: { from: 'empty', to: 'pause' },
play: { from: 'pause', to: 'play' },
pause: { from: ['play', 'empty'], to: 'pause' },
unload: { from: ['play', 'pause'], to: 'empty' }
});
state.is('empty'); // -> true
state.load();
state.is('pause'); // -> true
state.on('play', function(src) {
console.log(src); // -> 'eustia'
});
state.on('error', function(err, event) {
// Error handler
});
state.play('eustia');
Memory storage.
class Store extends Emitter {
constructor(data?: {});
set(key: string, val: any): void;
set(values: {}): void;
get(key: string): any;
get(keys: string[]): {};
remove(key: string): void;
remove(keys: string[]): void;
clear(): void;
each(fn: (...args: any[]) => void): void;
}
Extend from Emitter.
Name | Desc |
---|---|
data | Initial data |
Set value.
Name | Desc |
---|---|
key | Value key |
val | Value to set |
Set values.
Name | Desc |
---|---|
values | Key value pairs |
This emit a change event whenever is called.
Get value.
Name | Desc |
---|---|
key | Value key |
return | Value of given key |
Get values.
Name | Desc |
---|---|
keys | Array of keys |
return | Key value pairs |
Remove value.
Name | Desc |
---|---|
key | Key to remove |
Clear all data.
Iterate over values.
Name | Desc |
---|---|
fn | Function invoked per iteration |
const store = new Store('test');
store.set('user', { name: 'licia' });
store.get('user').name; // -> 'licia'
store.clear();
store.each(function(val, key) {
// Do something.
});
store.on('change', function(key, newVal, oldVal) {
// It triggers whenever set is called.
});
Parse, manipulate and generate chrome tracing data.
namespace Trace {
interface IEvent {
name: string;
cat: string;
ph: string;
ts: number;
pid: number;
tid: number;
args: any;
[key: string]: any;
}
class Process {
constructor(id);
id(): string;
name(): string;
addEvent(IEvent): void;
rmEvent(IEvent): void;
getThread(id: number): Thread;
rmThread(id: number): void;
threads(): Thread[];
toJSON(): IEvent[];
}
class Thread {
constructor(id, pid);
id(): string;
name(): string;
addEvent(IEvent): void;
rmEvent(IEvent): void;
events(): IEvent[];
toJSON(): IEvent[];
}
}
class Trace {
constructor(events: Trace.IEvent[]);
addEvent(event: Trace.IEvent);
rmEvent(event: Trace.IEvent);
getProcess(id: number): Trace.Process;
rmProcess(id: number): void;
processes(): Trace.Process[];
toJSON(): Trace.IEvent[];
}
const fs = require('fs');
const data = fs.readFileSync('path/to/trace', 'utf8');
const trace = new Trace(JSON.parse(data));
trace.rmProcess(627);
fs.writeFileSync(
'path/to/trace',
JSON.stringify(trace.toJSON()),
'utf8',
function() {}
);
Easily create chrome tracing data.
class Tracing {
constructor(options?: {
pid?: number;
tid?: number;
processName?: string;
threadName?: string;
});
start(cat?: string): void;
stop(): Trace.IEvent[];
metadata(name: string, args: any): void;
begin(cat: string, name: string, args?: any): void;
end(args?: any): void;
asyncBegin(cat: string, name: string, id?: string, args?: any): string;
asyncEnd(id: string, args?: any): void;
instant(
cat: string,
name: string,
scope?: 'g' | 'p' | 't',
args?: any
): void;
id(): string;
}
Name | Desc |
---|---|
options | Tracing options |
Available options:
Name | Desc |
---|---|
pid | Process id |
tid | Thread id |
processName | Process name |
threadName | Thread name |
Start recording.
Name | Desc |
---|---|
cat | Enabled categories |
Stop recording and get result events.
Record begin event.
Name | Desc |
---|---|
cat | Event categories |
name | Event name |
args | Arguments |
Record end event.
Record async begin event.
Record async end event.
Record instant event.
Get an unique id.
const fs = require('fs');
const tracing = new Tracing();
tracing.start();
tracing.begin('cat', 'name');
// Do something...
tracing.end();
fs.writeFileSync(
'path/to/trace',
JSON.stringify(tracing.stop()),
'utf8',
function() {}
);
Trie data structure.
class Trie {
add(word: string): void;
remove(word: string): void;
has(word: string): boolean;
words(prefix: string): string[];
clear(): void;
}
Add a word to trie.
Name | Desc |
---|---|
word | Word to add |
Remove a word from trie.
Check if word exists.
Get all words with given Prefix.
Name | Desc |
---|---|
prefix | Word prefix |
return | Words with given Prefix |
Clear all words from trie.
const trie = new Trie();
trie.add('carpet');
trie.add('car');
trie.add('cat');
trie.add('cart');
trie.has('cat'); // -> true
trie.remove('carpet');
trie.has('carpet'); // -> false
trie.words('car'); // -> ['car', 'cart']
trie.clear();
Tween engine for JavaScript animations.
class Tween extends Emitter {
constructor(target: any);
to(props: any, duration?: number, ease?: string | Function): Tween;
progress(): number;
progress(progress: number): Tween;
play(): Tween;
pause(): Tween;
paused(): boolean;
}
Extend from Emitter.
Name | Desc |
---|---|
obj | Values to tween |
Name | Desc |
---|---|
destination | Final properties |
duration | Tween duration |
ease | Easing function |
Begin playing forward.
Pause the animation.
Get animation paused state.
Update or get animation progress.
Name | Desc |
---|---|
progress | Number between 0 and 1 |
const pos = { x: 0, y: 0 };
const tween = new Tween(pos);
tween
.on('update', function(target) {
console.log(target.x, target.y);
})
.on('end', function(target) {
console.log(target.x, target.y); // -> 100, 100
});
tween.to({ x: 100, y: 100 }, 1000, 'inElastic').play();
Simple url manipulator.
namespace Url {
interface IUrl {
protocol: string;
auth: string;
hostname: string;
hash: string;
query: any;
port: string;
pathname: string;
slashes: boolean;
}
}
class Url {
protocol: string;
auth: string;
hostname: string;
hash: string;
query: any;
port: string;
pathname: string;
slashes: boolean;
constructor(url?: string);
setQuery(name: string, val: string | number): Url;
setQuery(query: types.PlainObj<string | number>): Url;
rmQuery(name: string | string[]): Url;
toString(): string;
static parse(url: string): Url.IUrl;
static stringify(object: Url.IUrl): string;
}
Name | Desc |
---|---|
url=location | Url string |
Set query value.
Name | Desc |
---|---|
name | Query name |
val | Query value |
return | this |
Name | Desc |
---|---|
query | query object |
return | this |
Remove query value.
Name | Desc |
---|---|
name | Query name |
return | this |
[static] Parse url into an object.
Name | Desc |
---|---|
url | Url string |
return | Url object |
[static] Stringify url object into a string.
Name | Desc |
---|---|
url | Url object |
return | 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 (#) |
const url = new Url('http://example.com:8080?eruda=true');
console.log(url.port); // -> '8080'
url.query.foo = 'bar';
url.rmQuery('eruda');
url.toString(); // -> 'http://example.com:8080/?foo=bar'
Object values validation.
class Validator {
constructor(options: types.PlainObj<any>);
validate(object: any): string | boolean;
static plugins: any;
static addPlugin(name: string, plugin: types.AnyFn): void;
}
Name | Desc |
---|---|
options | Validation configuration |
Validate object.
Name | Desc |
---|---|
obj | Object to validate |
return | Validation result, true means ok |
[static] Add plugin.
Name | Desc |
---|---|
name | Plugin name |
plugin | 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';
});
const validator = new Validator({
test: {
required: true,
custom: true
}
});
validator.validate({}); // -> 'test is required'
validator.validate({ test: 1 }); // -> 'test should be a string with length 5';
validator.validate({ test: 'licia' }); // -> true
Weighted Round Robin implementation.
class Wrr {
size: number;
set(val: any, weight: number): void;
get(val: any): number | void;
remove(val: any): void;
clear(): void;
next(): any;
}
Pool size.
Set a value to the pool. Weight is updated if value already exists.
Name | Desc |
---|---|
val | Value to set |
weight | Weight of the value |
Get weight of given value.
Name | Desc |
---|---|
val | Value to get |
return | Weight of the value |
Remove given value.
Name | Desc |
---|---|
val | Value to remove |
Get next value from pool.
Clear all values.
const pool = new Wrr();
pool.set('A', 4);
pool.set('B', 8);
pool.set('C', 2);
pool.next();
pool.remove('A');
console.log(pool.size); // -> 2
Calculate the set of unique abbreviations for a given set of strings.
function abbrev(...names: string[]): types.PlainObj<string>;
Name | Desc |
---|---|
names | List of names |
return | 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.
function after<T extends types.AnyFn>(n: number, fn: T): T;
Name | Desc |
---|---|
n | Number of calls before invoked |
fn | Function to restrict |
return | New restricted function |
const fn = after(5, function() {
// -> Only invoke after fn is called 5 times.
});
Perform an asynchronous HTTP request.
namespace ajax {
function get(
url: string,
data: string | {},
success: types.AnyFn,
dataType?: string
): XMLHttpRequest;
function get(
url: string,
success: types.AnyFn,
dataType?: string
): XMLHttpRequest;
function post(
url: string,
data: string | {},
success: types.AnyFn,
dataType?: string
): XMLHttpRequest;
function post(
url: string,
success: types.AnyFn,
dataType?: string
): XMLHttpRequest;
}
function ajax(options: {
type?: string;
url: string;
data?: string | {};
dataType?: string;
contentType?: string;
success?: types.AnyFn;
error?: types.AnyFn;
complete?: types.AnyFn;
timeout?: number;
}): XMLHttpRequest;
Name | Desc |
---|---|
options | Ajax options |
Available options:
Name | Desc |
---|---|
type=get | Request type |
url | Request url |
data | Request data |
dataType=json | Response type(json, xml) |
contentType=application/x-www-form-urlencoded | Request header Content-Type |
success | Success callback |
error | Error callback |
complete | Callback after request |
timeout | Request timeout |
Shortcut for type = GET;
Shortcut for type = POST;
Name | Desc |
---|---|
url | Request url |
data | Request data |
success | Success callback |
dataType | Response type |
ajax({
url: 'http://example.com',
data: { test: 'true' },
error() {},
success(data) {
// ...
},
dataType: 'json'
});
ajax.get('http://example.com', {}, function(data) {
// ...
});
Retrieve all the names of object's own and inherited properties.
namespace allKeys {
interface IOptions {
prototype?: boolean;
unenumerable?: boolean;
}
}
function allKeys(
obj: any,
options: { symbol: true } & allKeys.IOptions
): Array<string | Symbol>;
function allKeys(
obj: any,
options?: ({ symbol: false } & allKeys.IOptions) | allKeys.IOptions
): string[];
Name | Desc |
---|---|
obj | Object to query |
options | Options |
return | Array of all property names |
Available options:
Name | Desc |
---|---|
prototype=true | Include prototype keys |
unenumerable=false | Include unenumerable keys |
symbol=false | Include symbol keys |
Members of Object's prototype won't be retrieved.
const obj = Object.create({ zero: 0 });
obj.one = 1;
allKeys(obj); // -> ['zero', 'one']
Ansi colors.
namespace ansiColor {
type IFn = (str: string) => string;
}
const ansiColor: {
black: ansiColor.IFn;
red: ansiColor.IFn;
green: ansiColor.IFn;
yellow: ansiColor.IFn;
blue: ansiColor.IFn;
magenta: ansiColor.IFn;
cyan: ansiColor.IFn;
white: ansiColor.IFn;
gray: ansiColor.IFn;
grey: ansiColor.IFn;
bgBlack: ansiColor.IFn;
bgRed: ansiColor.IFn;
bgGreen: ansiColor.IFn;
bgYellow: ansiColor.IFn;
bgBlue: ansiColor.IFn;
bgMagenta: ansiColor.IFn;
bgCyan: ansiColor.IFn;
bgWhite: ansiColor.IFn;
blackBright: ansiColor.IFn;
redBright: ansiColor.IFn;
greenBright: ansiColor.IFn;
yellowBright: ansiColor.IFn;
blueBright: ansiColor.IFn;
magentaBright: ansiColor.IFn;
cyanBright: ansiColor.IFn;
whiteBright: ansiColor.IFn;
bgBlackBright: ansiColor.IFn;
bgRedBright: ansiColor.IFn;
bgGreenBright: ansiColor.IFn;
bgYellowBright: ansiColor.IFn;
bgBlueBright: ansiColor.IFn;
bgMagentaBright: ansiColor.IFn;
bgCyanBright: ansiColor.IFn;
bgWhiteBright: ansiColor.IFn;
};
black, red, green, yellow, blue, magenta, cyan, white, gray, grey
bgBlack, bgRed, bgGreen, bgYellow, bgBlue, bgMagenta, bgCyan, bgWhite,
blackBright, redBright, greenBright, yellowBright, blueBright, magentaBright, cyanBright, whiteBright
bgBlackBright, bgRedBright, bgGreenBright, bgYellowBright, bgBlueBright, bgMagentaBright, bgCyanBright, bgWhiteBright
ansiColor.red('Warning');
Make an object map using array of strings.
function arrToMap<T>(
arr: string[],
val?: T
): { [key: string]: T };
Name | Desc |
---|---|
arr | Array of strings |
val=true | Key value |
return | Object map |
const needPx = arrToMap([
'column-count',
'columns',
'font-weight',
'line-weight',
'opacity',
'z-index',
'zoom'
]);
const key = 'column-count';
let val = '5';
if (needPx[key]) val += 'px';
console.log(val); // -> '5px'
Use Buffer to emulate atob when running in node.
function atob(str: string): string;
atob('SGVsbG8gV29ybGQ='); // -> 'Hello World'
Get average value of given numbers.
function average(...numbers: number[]): number;
Name | Desc |
---|---|
numbers | Numbers to calculate |
return | Average value |
average(5, 3, 1); // -> 3
Basic base64 encoding and decoding.
const base64: {
encode(bytes: number[]): string;
decode(str: string): number[];
};
Turn a byte array into a base64 string.
Name | Desc |
---|---|
bytes | Byte array |
return | Base64 string |
Turn a base64 string into a byte array.
Name | Desc |
---|---|
str | Base64 string |
return | Byte array |
base64.encode([168, 174, 155, 255]); // -> 'qK6b/w=='
base64.decode('qK6b/w=='); // -> [168, 174, 155, 255]
Create a function that invokes less than n times.
function before<T extends types.AnyFn>(n: number, fn: T): T;
Name | Desc |
---|---|
n | Number of calls at which fn is no longer invoked |
fn | Function to restrict |
return | New restricted function |
Subsequent calls to the created function return the result of the last fn invocation.
const fn = before(5, function() {});
fn(); // Allow function to be call 4 times at last.
Binary search implementation.
function binarySearch(
array: any[],
val: any,
cmp?: types.AnyFn
): number;
Name | Desc |
---|---|
array | Sorted array |
val | Value to seek |
cmp | Comparator |
return | Value index |
binarySearch([1, 2, 3], 2); // -> 1
binarySearch([1, 2], 3); // -> -1
binarySearch(
[
{
key: 1
},
{
key: 2
}
],
{ key: 1 },
(a, b) => {
if (a.key === b.key) return 0;
return a.key < b.key ? -1 : 1;
}
); // -> 0
Create a function bound to a given object.
function bind(
fn: types.AnyFn,
ctx: any,
...args: any[]
): types.AnyFn;
Name | Desc |
---|---|
fn | Function to bind |
ctx | This binding of given fn |
args | Optional arguments |
return | New bound function |
const fn = bind(
function(msg) {
console.log(this.name + ':' + msg);
},
{ name: 'eustia' },
'I am a utility library.'
);
fn(); // -> 'eustia: I am a utility library.'
Use Buffer to emulate btoa when running in node.
function btoa(str: string): string;
btoa('Hello World'); // -> 'SGVsbG8gV29ybGQ='
Bubble sort implementation.
function bubbleSort(arr: any[], cmp?: types.AnyFn): any[];
Name | Desc |
---|---|
arr | Array to sort |
cmp | Comparator |
return | Sorted array |
bubbleSort([2, 1]); // -> [1, 2]
Convert bytes to string.
function bytesToStr(bytes: number[], encoding?: string): string;
Name | Desc |
---|---|
bytes | Bytes array |
encoding=utf8 | Encoding of string |
return | Result string |
bytesToStr([108, 105, 99, 105, 97]); // -> 'licia'
Convert bytes to 32-bit words.
function bytesToWords(bytes: number[]): number[];
Useful when using CryptoJS.
Name | Desc |
---|---|
bytes | Byte array |
return | Word array |
bytesToWords([0x12, 0x34, 0x56, 0x78]); // -> [0x12345678]
Cache everything in module require to speed up app load.
function cacheRequire(options?: {
dir?: string;
requirePath?: boolean;
code?: boolean;
compileCache?: boolean;
}): void;
Name | Desc |
---|---|
options | Cache options |
Available options:
Name | Desc |
---|---|
dir | Cache dir |
requirePath=true | Whether require path should be cached |
code=false | Whether js code should be cached |
compileCache=true | Whether compile cache should be used |
cacheRequire({
dir: 'path/to/cache/dir'
});
Convert a function that returns a Promise to a function following the error-first callback style.
function callbackify(fn: types.AnyFn): types.AnyFn;
Name | Desc |
---|---|
fn | Function that returns a Promise |
return | Function following the error-fist callback style |
function fn() {
return new Promise(function(resolve, reject) {
// ...
});
}
const cbFn = callbackify(fn);
cbFn(function(err, value) {
// ...
});
Convert string to "camelCase".
function camelCase(str: string): string;
Name | Desc |
---|---|
str | String to convert |
return | 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.
function capitalize(str: string): string;
Name | Desc |
---|---|
str | String to capitalize |
return | Capitalized string |
capitalize('rED'); // -> Red
Cast value into a property path array.
function castPath(path: string | string[], obj?: any): string[];
Name | Desc |
---|---|
path | Value to inspect |
obj | Object to query |
return | 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.
function centerAlign(
str: string | string[],
width?: number
): string;
Name | Desc |
---|---|
str | String to align |
width | Total width of each line |
return | Center aligned string |
centerAlign('test', 8); // -> ' test'
centerAlign('test\nlines', 8); // -> ' test\n lines'
centerAlign(['test', 'lines'], 8); // -> ' test\n lines'
Read cgroup metrics inside container.
const cgroup: {
cpu: {
stat(): {
usage: number;
};
max(): number;
};
cpuset: {
cpus(): {
effective: number[];
};
};
memory: {
max(): number;
current(): number;
};
version(): number;
};
cgroup.cpu.stat();
Return string representing a character whose Unicode code point is the given integer.
function char(num: number): string;
Name | Desc |
---|---|
num | Integer to convert |
return | String representing corresponding char |
char(65); // -> 'A'
char(97); // -> 'a'
Split array into groups the length of given size.
function chunk(arr: any[], size?: number): Array<any[]>;
Name | Desc |
---|---|
arr | Array to process |
size=1 | Length of each chunk |
return | Chunks of given size |
chunk([1, 2, 3, 4], 2); // -> [[1, 2], [3, 4]]
chunk([1, 2, 3, 4], 3); // -> [[1, 2, 3], [4]]
chunk([1, 2, 3, 4]); // -> [[1], [2], [3], [4]]
Clamp number within the inclusive lower and upper bounds.
function clamp(n: number, lower: number, upper: number): number;
function clamp(n: number, upper: number): number;
Name | Desc |
---|---|
n | Number to clamp |
lower | Lower bound |
upper | Upper bound |
return | 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.
function className(...names: any[]): string;
Name | Desc |
---|---|
names | Class names |
return | 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';
Output cli help.
namespace cliHelp {
interface IOption {
name: string;
shorthand?: string;
desc: string;
}
interface ICommand {
name: string;
desc: string;
usage: string | string[];
options?: IOption[];
}
interface IData {
name: string;
usage: string | string[];
commands: ICommand[];
}
}
function cliHelp(data: cliHelp.IData | cliHelp.ICommand): string;
Name | Desc |
---|---|
data | Help data |
return | Cli help |
const test = {
name: 'test',
desc: 'Generate test files',
usage: ['<module-name> [options]', 'lpad --browser'],
options: [
{
name: 'browser',
shorthand: 'b',
desc: 'True if test should run in a browser'
}
]
};
const data = {
name: 'licia',
usage: '<command> [options]',
commands: [test]
};
cliHelp(data);
cliHelp(test);
Create a shallow-copied clone of the provided plain object.
function clone<T>(val: T): T;
Any nested objects or arrays will be copied by reference, not duplicated.
Name | Desc |
---|---|
val | Value to clone |
return | Cloned value |
clone({ name: 'eustia' }); // -> {name: 'eustia'}
Recursively clone value.
function cloneDeep<T>(val: T): T;
Name | Desc |
---|---|
val | Value to clone |
return | Deep cloned Value |
const obj = [{ a: 1 }, { a: 2 }];
const obj2 = cloneDeep(obj);
console.log(obj[0] === obj2[1]); // -> false
Compare version strings.
function cmpVersion(v1: string, v2: string): number;
Name | Desc |
---|---|
v1 | Version to compare |
v2 | Version to compare |
return | 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
Create an array by using one array for keys and another for its values.
function combine(keys: string[], values: any[]): any;
Name | Desc |
---|---|
keys | Keys to be used |
values | Values to be used |
return | Created object |
combine(['a', 'b', 'c'], [1, 2, 3]); // -> {a: 1, b: 2, c: 3}
Return a copy of the array with all falsy values removed.
function compact(arr: any[]): any[];
The values false, null, 0, "", undefined, and NaN are falsey.
Name | Desc |
---|---|
arr | Array to compact |
return | New array of filtered values |
compact([0, 1, false, 2, '', 3]); // -> [1, 2, 3]
Compose a list of functions.
function compose(...fn: types.AnyFn[]): types.AnyFn;
Each function consumes the return value of the function that follows.
Name | Desc |
---|---|
...fn | Functions to compose |
return | Composed function |
const welcome = compose(
function(name) {
return 'hi: ' + name;
},
function(name) {
return name.toUpperCase() + '!';
}
);
welcome('licia'); // -> 'hi: LICIA!'
Compress image using canvas.
function compressImg(
file: File | Blob | string,
cb: types.AnyFn
): void;
function compressImg(
file: File | Blob | string,
options?: {
maxWidth?: number;
maxHeight?: number;
width?: number;
height?: number;
mimeType?: string;
quality?: number;
},
cb?: types.AnyFn
): void;
Name | Desc |
---|---|
file | Image file or url |
options | Options |
cb | Callback |
Available options:
Name | Desc |
---|---|
maxWidth | Max width |
maxHeight | Max height |
width | Output image width |
height | Output image height |
mimeType | Mime type |
quality=0.8 | 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.
const file = new Blob([]);
compressImg(
file,
{
maxWidth: 200
},
function(err, file) {
// ...
}
);
Concat multiple arrays into a single array.
function concat(...args: Array<any[]>): any[];
Name | Desc |
---|---|
...arr | Arrays to concat |
return | Concatenated array |
concat([1, 2], [3], [4, 5]); // -> [1, 2, 3, 4, 5]
Check if the value is present in the list.
function contain(arr: any[] | {} | string, val: any): boolean;
Name | Desc |
---|---|
target | Target object |
val | Value to check |
return | True if value is present in the list |
contain([1, 2, 3], 1); // -> true
contain({ a: 1, b: 2 }, 1); // -> true
contain('abc', 'a'); // -> true
Get container stats inside container.
const container: {
cpuNum(): number;
cpuUsage(period?: number): Promise<number>;
cpuLoad(period?: number): Promise<number>;
memUsage(): number;
memLoad(): number;
};
container.cpuNum();
Convert base of a number.
function convertBase(
num: number | string,
from: number,
to: number
): string;
Name | Desc |
---|---|
num | Number to convert |
from | Base from |
to | Base to |
return | Converted number |
convertBase('10', 2, 10); // -> '2'
convertBase('ff', 16, 2); // -> '11111111'
Convert binary data type.
namespace convertBin {
function blobToArrBuffer(blob: any): Promise<ArrayBuffer>;
}
function convertBin(bin: any, type: string): any;
Name | Desc |
---|---|
bin | Binary data to convert |
type | Binary type |
return | Target binary |
base64, ArrayBuffer, Array, Uint8Array, Blob(browser), Buffer(node)
You can not convert Blob to other types directly since it's an asynchronous process.
Convert Blob to ArrayBuffer.
Name | Desc |
---|---|
blob | Blob to convert |
return | ArrayBuffer promise |
convertBin('qK6b/w==', 'Uint8Array'); // -> [168, 174, 155, 255]
convertBin.blobToArrBuffer(new Blob([])).then(arrBuffer => {
// Do something...
});
Simple api for handling browser cookies.
namespace cookie {
interface IOptions {
path?: string;
expires?: number;
domain?: string;
secure?: boolean;
}
interface ICookie {
get(key: string, options?: cookie.IOptions): string;
set(key: string, val: string, options?: cookie.IOptions): ICookie;
remove(key: string, options?: cookie.IOptions): ICookie;
}
}
const cookie: cookie.ICookie;
Get cookie value.
Name | Desc |
---|---|
key | Cookie key |
return | Corresponding cookie value |
Set cookie value.
Name | Desc |
---|---|
key | Cookie key |
val | Cookie value |
options | Cookie options |
return | Module cookie |
Remove cookie value.
Name | Desc |
---|---|
key | Cookie key |
options | Cookie options |
return | Module cookie |
cookie.set('a', '1', { path: '/' });
cookie.get('a'); // -> '1'
cookie.remove('a');
Copy text to clipboard using document.execCommand.
function copy(text: string, cb?: types.AnyFn): void;
Name | Desc |
---|---|
text | Text to copy |
cb | Optional callback |
copy('text', function(err) {
// Handle errors.
});
CRC1 implementation.
function crc1(
input: string | number[],
previous?: number
): number;
Name | Desc |
---|---|
input | Data to calculate |
previous | Previous CRC1 result |
return | CRC1 result |
crc1('1234567890').toString(16); // -> 'd'
CRC16 implementation.
function crc16(
input: string | number[],
previous?: number
): number;
Name | Desc |
---|---|
input | Data to calculate |
previous | Previous CRC16 result |
return | CRC16 result |
crc16('1234567890').toString(16); // -> 'c57a'
CRC32 implementation.
function crc32(
input: string | number[],
previous?: number
): number;
Name | Desc |
---|---|
input | Data to calculate |
previous | Previous CRC32 result |
return | CRC16 result |
crc32('1234567890').toString(16); // -> '261daee5'
CRC8 implementation.
function crc8(
input: string | number[],
previous?: number
): number;
Name | Desc |
---|---|
input | Data to calculate |
previous | Previous CRC8 result |
return | CRC8 result |
crc8('1234567890').toString(16); // -> '52'
Create new object using given object as prototype.
function create(proto?: object): any;
Name | Desc |
---|---|
proto | Prototype of new object |
return | Created object |
const obj = create({ a: 1 });
console.log(obj.a); // -> 1
Used to create extend, extendOwn and defaults.
function createAssigner(
keysFn: types.AnyFn,
defaults: boolean
): types.AnyFn;
Name | Desc |
---|---|
keysFn | Function to get object keys |
defaults | No override when set to true |
return | Result function, extend... |
CreateObjectURL wrapper.
function createUrl(
data: any,
options?: { type?: string }
): string;
Name | Desc |
---|---|
data | Url data |
options | Used when data is not a File or Blob |
return | Blob url |
createUrl('test', { type: 'text/plain' }); // -> Blob url
createUrl(['test', 'test']);
createUrl(new Blob([]));
createUrl(new File(['test'], 'test.txt'));
Css parser and serializer.
const css: {
parse(css: string): object;
stringify(stylesheet: object, options?: { indent?: string }): string;
};
Comments will be stripped.
Parse css into js object.
Name | Desc |
---|---|
css | Css string |
return | Parsed js object |
Stringify object into css.
Name | Desc |
---|---|
stylesheet | Object to stringify |
options | Stringify options |
return | Css string |
Options:
Name | Desc |
---|---|
indent=' ' | String used to indent |
const stylesheet = css.parse('.name { background: #000; color: red; }');
// {type: 'stylesheet', rules: [{type: 'rule', selector: '.name', declarations: [...]}]}
css.stringify(stylesheet);
Calculate and compare priority of css selector/rule.
namespace cssPriority {
function compare(p1: number[], p2: number[]): number;
}
function cssPriority(
selector: string,
options?: {
important?: boolean;
inlineStyle?: boolean;
position?: number;
}
): number[];
Name | Type |
---|---|
selector | CSS selector |
options | Rule extra info |
return | Priority array |
Priority array contains five number values.
Compare priorities.
Name | Desc |
---|---|
p1 | Priority to compare |
p2 | Priority to compare |
return | Comparison result |
cssPriority('a.button > i.icon:before', {
important: true,
inlineStyle: false,
position: 100
}); // -> [1, 0, 0, 2, 3, 100]
Check if browser supports a given CSS feature.
function cssSupports(name: string, val?: string): boolean;
Name | Desc |
---|---|
name | Css property name |
val | Css property value |
return | 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.
function curry(fn: types.AnyFn): types.AnyFn;
Name | Desc |
---|---|
fn | Function to curry |
return | New curried function |
const add = curry(function(a, b) {
return a + b;
});
const add1 = add(1);
add1(2); // -> 3
Simple but extremely useful date format function.
function dateFormat(
date: Date,
mask: string,
utc?: boolean,
gmt?: boolean
): string;
function dateFormat(
mask: string,
utc?: boolean,
gmt?: boolean
): string;
Name | Desc |
---|---|
date=new Date | Date object to format |
mask | Format mask |
utc=false | UTC or not |
gmt=false | GMT or not |
return | Formatted duration |
Mask | Desc |
---|---|
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.
function debounce<T extends types.AnyFn>(fn: T, wait: number): T;
Name | Desc |
---|---|
fn | Function to debounce |
wait | Number of milliseconds to delay |
return | New debounced function |
const calLayout = debounce(function() {}, 300);
// $(window).resize(calLayout);
A tiny JavaScript debugging utility.
function debug(name: string): any;
Name | Desc |
---|---|
name | Namespace |
return | Function to print decorated log |
const d = debug('test');
d('doing lots of uninteresting work');
d.enabled = false;
Convert Latin-1 Supplement and Latin Extended-A letters to basic Latin letters and remove combining diacritical marks.
function deburr(str: string): string;
Name | Desc |
---|---|
str | String to deburr |
return | Deburred string |
deburr('déjà vu'); // -> 'deja vu'
Better decodeURIComponent that does not throw if input is invalid.
function decodeUriComponent(str: string): string;
Name | Desc |
---|---|
str | String to decode |
return | 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.
function defaults(obj: any, ...src: any[]): any;
Name | Desc |
---|---|
obj | Destination object |
...src | Sources objects |
return | Destination object |
defaults({ name: 'RedHood' }, { name: 'Unknown', age: 24 }); // -> {name: 'RedHood', age: 24}
Define a module, should be used along with use.
function define(
name: string,
requires: string[],
method: types.AnyFn
): void;
function define(name: string, method: types.AnyFn): void;
Name | Desc |
---|---|
name | Module name |
requires | Dependencies |
method | 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).
function defineProp<T>(
obj: T,
prop: string,
descriptor: PropertyDescriptor
): T;
function defineProp<T>(
obj: T,
descriptor: PropertyDescriptorMap
): T;
Name | Desc |
---|---|
obj | Object to define |
prop | Property path |
descriptor | Property descriptor |
return | Object itself |
Name | Desc |
---|---|
obj | Object to define |
prop | Property descriptors |
return | Object itself |
const obj = { b: { c: 3 }, d: 4, e: 5 };
defineProp(obj, 'a', {
get: function() {
return this.e * 2;
}
});
// obj.a is equal to 10
defineProp(obj, 'b.c', {
set: function(val) {
// this is pointed to obj.b
this.e = val;
}.bind(obj)
});
obj.b.c = 2;
// obj.a is equal to 4
const obj2 = { a: 1, b: 2, c: 3 };
defineProp(obj2, {
a: {
get: function() {
return this.c;
}
},
b: {
set: function(val) {
this.c = val / 2;
}
}
});
// obj2.a is equal to 3
obj2.b = 4;
// obj2.a is equal to 2
Return the first argument that is not undefined.
function defined(...args: any[]): any;
Name | Desc |
---|---|
...args | Arguments to check |
return | First defined argument |
defined(false, 2, void 0, 100); // -> false
Delete node.js require cache.
function delRequireCache(id: string): void;
Name | Desc |
---|---|
id | Module name or path |
const licia = require('licia');
licia.a = 5;
delRequireCache('licia');
require('licia').a; // -> undefined
Invoke function after certain milliseconds.
function delay(
fn: types.AnyFn,
wait: number,
...args: any[]
): void;
Name | Desc |
---|---|
fn | Function to delay |
wait | 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.
const delegate: {
add(el: Element, type: string, selector: string, cb: types.AnyFn): void;
remove(el: Element, type: string, selector: string, cb: types.AnyFn): void;
};
Add event delegation.
Name | Desc |
---|---|
el | Parent element |
type | Event type |
selector | Match selector |
cb | Event callback |
Remove event delegation.
const container = document.getElementById('container');
function clickHandler() {
// Do something...
}
delegate.add(container, 'click', '.children', clickHandler);
delegate.remove(container, 'click', '.children', clickHandler);
Node.js util.deprecate with browser support.
function deprecate(fn: types.AnyFn, msg: string): types.AnyFn;
Name | Desc |
---|---|
fn | Function to be deprecated |
msg | Warning message |
return | Deprecated function |
const fn = () => {};
const obsoleteFn = deprecate(fn, 'obsoleteFn is deprecated.');
obsoleteFn();
Detect browser info using ua.
function detectBrowser(
ua?: string
): {
name: string;
version: number;
};
Name | Desc |
---|---|
ua=navigator.userAgent | Browser userAgent |
return | Object containing name and version |
Browsers supported: ie, chrome, edge, firefox, opera, safari, ios(mobile safari), android(android browser)
const browser = detectBrowser();
if (browser.name === 'ie' && browser.version < 9) {
// Do something about old IE...
}
Detect if mocha is running.
function detectMocha(): boolean;
detectMocha(); // -> True if mocha is running.
Detect operating system using ua.
function detectOs(ua?: string): string;
Name | Desc |
---|---|
ua=navigator.userAgent | Browser userAgent |
return | 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.
function difference(arr: any[], ...args: any[]): any[];
Name | Desc |
---|---|
arr | Array to inspect |
...args | Values to exclude |
return | New array of filtered values |
difference([3, 2, 1], [4, 2]); // -> [3, 1]
Convert string to "dotCase".
function dotCase(str: string): string;
Name | Desc |
---|---|
str | String to convert |
return | Dot cased string |
dotCase('fooBar'); // -> foo.bar
dotCase('foo bar'); // -> foo.bar
Trigger a file download on client side.
function download(
data: Blob | File | string | any[],
name: string,
type?: string
): void;
Name | Desc |
---|---|
data | Data to download |
name | File name |
type=text/plain | Data type |
download('test', 'test.txt');
Simple duration format function.
function durationFormat(duration: number, mask?: string): string;
Name | Desc |
---|---|
duration | Duration to format, millisecond |
mask='hh:mm:ss' | Format mask |
return | Formatted duration |
Mask | Desc |
---|---|
d | Days |
h | Hours |
m | Minutes |
s | Seconds |
l | Milliseconds |
durationFormat(12345678); // -> '03:25:45'
durationFormat(12345678, 'h:m:s:l'); // -> '3:25:45:678'
Iterate over elements of collection and invokes iterator for each element.
function each<T>(
list: types.List<T>,
iterator: types.ListIterator<T, void>,
ctx?: any
): types.List<T>;
function each<T>(
object: types.Dictionary<T>,
iterator: types.ObjectIterator<T, void>,
ctx?: any
): types.Collection<T>;
Name | Desc |
---|---|
obj | Collection to iterate over |
iterator | Function invoked per iteration |
ctx | Function context |
each({ a: 1, b: 2 }, function(val, key) {});
Easing functions adapted from http://jqueryui.com/ .
const easing: {
linear(percent: number): number;
inQuad(percent: number): number;
outQuad(percent: number): number;
inOutQuad(percent: number): number;
outInQuad(percent: number): number;
inCubic(percent: number): number;
outCubic(percent: number): number;
inQuart(percent: number): number;
outQuart(percent: number): number;
inQuint(percent: number): number;
outQuint(percent: number): number;
inExpo(percent: number): number;
outExpo(percent: number): number;
inSine(percent: number): number;
outSine(percent: number): number;
inCirc(percent: number): number;
outCirc(percent: number): number;
inElastic(percent: number, elasticity?: number): number;
outElastic(percent: number, elasticity?: number): number;
inBack(percent: number): number;
outBack(percent: number): number;
inOutBack(percent: number): number;
outInBack(percent: number): number;
inBounce(percent: number): number;
outBounce(percent: number): number;
};
Name | Desc |
---|---|
percent | Number between 0 and 1 |
return | Calculated number |
easing.linear(0.5); // -> 0.5
easing.inElastic(0.5, 500); // -> 0.03125
Emulate touch events on desktop browsers.
function emulateTouch(el: Element): void;
Name | Desc |
---|---|
el | Target element |
const el = document.querySelector('#test');
emulateTouch(el);
el.addEventListener('touchstart', () => {}, false);
Check if string ends with the given target string.
function endWith(str: string, suffix: string): boolean;
Name | Desc |
---|---|
str | The string to search |
suffix | String suffix |
return | True if string ends with target |
endWith('ab', 'b'); // -> true
Escapes a string for insertion into HTML, replacing &, <, >, ", `, and ' characters.
function escape(str: string): string;
Name | Desc |
---|---|
str | String to escape |
return | Escaped string |
escape('You & Me'); // -> 'You & Me'
Escape string to be a valid JavaScript string literal between quotes.
function escapeJsStr(str: string): string;
http://www.ecma-international.org/ecma-262/5.1/#sec-7.8.4
Name | Desc |
---|---|
str | String to escape |
return | Escaped string |
escapeJsStr('"\n'); // -> '\\"\\\\n'
Escape special chars to be used as literals in RegExp constructors.
function escapeRegExp(str: string): string;
Name | Desc |
---|---|
str | String to escape |
return | Escaped string |
escapeRegExp('[licia]'); // -> '\\[licia\\]'
Load css into page.
function evalCss(css: string): HTMLStyleElement;
Name | Desc |
---|---|
css | Css code |
return | Style element |
evalCss('body{background:#08c}');
Execute js in given context.
function evalJs(js: string, ctx?: any): void;
Name | Desc |
---|---|
js | JavaScript code |
ctx=global | Context |
evalJs('5+2'); // -> 7
evalJs('this.a', { a: 2 }); // -> 2
Check if predicate return truthy for all elements.
function every<T>(
object: types.List<T>,
iterator?: types.ListIterator<T, boolean>,
context?: any
): boolean;
function every<T>(
object: types.Dictionary<T>,
iterator?: types.ObjectIterator<T, boolean>,
context?: any
): boolean;
Name | Desc |
---|---|
object | Collection to iterate over |
iterator | Function invoked per iteration |
context | Predicate context |
return | True if all elements pass the predicate check |
every([2, 4], function(val) {
return val % 2 === 0;
}); // -> true
Copy all of the properties in the source objects over to the destination object.
function extend(destination: any, ...sources: any[]): any;
Name | Desc |
---|---|
destination | Destination object |
...sources | Sources objects |
return | Destination object |
extend({ name: 'RedHood' }, { age: 24 }); // -> {name: 'RedHood', age: 24}
Recursive object extending.
function extendDeep(destination: any, ...sources: any[]): any;
Name | Desc |
---|---|
destination | Destination object |
...sources | Sources objects |
return | 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.
function extendOwn(destination: any, ...sources: any[]): any;
Name | Desc |
---|---|
destination | Destination object |
...sources | Sources objects |
return | Destination object |
extendOwn({ name: 'RedHood' }, { age: 24 }); // -> {name: 'RedHood', age: 24}
Extract block comments from source code.
function extractBlockCmts(str: string): string[];
Name | Desc |
---|---|
str | String to extract |
return | Block comments |
extractBlockCmts('\/*licia*\/'); // -> ['licia']
Extract urls from plain text.
function extractUrls(str: string): string[];
Name | Desc |
---|---|
str | Text to extract |
return | Url list |
const str =
'[Official site: http://eustia.liriliri.io](http://eustia.liriliri.io)';
extractUrls(str); // -> ['http://eustia.liriliri.io']
Turn XMLHttpRequest into promise like.
namespace fetch {
interface IResult {
ok: boolean;
status: number;
statusText: string;
url: string;
clone(): IResult;
text(): Promise<string>;
json(): Promise<any>;
xml(): Promise<Document | null>;
blob(): Promise<Blob>;
headers: {
keys(): string[];
entries(): Array<string[]>;
get(name: string): string;
has(name: string): boolean;
};
}
}
function fetch(
url: string,
options?: {
method?: string;
timeout?: number;
headers?: types.PlainObj<string>;
body?: any;
}
): Promise<fetch.IResult>;
Note: This is not a complete fetch pollyfill.
Name | Desc |
---|---|
url | Request url |
options | Request options |
return | 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.
function fibonacci(n: number): number;
Name | Desc |
---|---|
n | Index of fibonacci sequence |
return | Expected fibonacci number |
fibonacci(1); // -> 1
fibonacci(3); // -> 2
Turn bytes into human readable file size.
function fileSize(bytes: number): string;
Name | Desc |
---|---|
bytes | File bytes |
return | Readable file size |
fileSize(5); // -> '5'
fileSize(1500); // -> '1.46K'
fileSize(1500000); // -> '1.43M'
fileSize(1500000000); // -> '1.4G'
fileSize(1500000000000); // -> '1.36T'
Detect file type using magic number.
function fileType(
input: Buffer | ArrayBuffer | Uint8Array
):
| {
ext: string;
mime: string;
}
| undefined;
Name | Desc |
---|---|
input | File input |
return | Object containing ext and mime |
jpg, png, gif, webp, bmp, gz, zip, rar, pdf, exe
const fs = require('fs');
const file = fs.readFileSync('path/to/file');
console.log(fileType(file)); // -> { ext: 'jpg', mime: 'image/jpeg' }
Convert a file path to a file URL.
function fileUrl(path: string): string;
Name | Desc |
---|---|
path | File path |
return | File URL |
fileUrl('c:\\foo\\bar'); // -> 'file:///c:/foo/bar'
Fill elements of array with value.
function fill(
list: any[],
val: any,
start?: number,
end?: number
): any[];
Name | Desc |
---|---|
list | Array to fill |
val | Value to fill array with |
start=0 | Start position |
end=arr.length | End position |
return | 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.
function filter<T>(
list: types.List<T>,
iterator: types.ListIterator<T, boolean>,
context?: any
): T[];
function filter<T>(
object: types.Dictionary<T>,
iterator: types.ObjectIterator<T, boolean>,
context?: any
): T[];
Name | Desc |
---|---|
obj | Collection to iterate over |
predicate | Function invoked per iteration |
ctx | Predicate context |
return | 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.
function find<T>(
object: types.List<T>,
iterator: types.ListIterator<T, boolean>,
context?: any
): T | undefined;
function find<T>(
object: types.Dictionary<T>,
iterator: types.ObjectIterator<T, boolean>,
context?: any
): T | undefined;
Name | Desc |
---|---|
object | Collection to iterate over |
iterator | Function invoked per iteration |
context | Predicate context |
return | First value that passes predicate |
find(
[
{
name: 'john',
age: 24
},
{
name: 'jane',
age: 23
}
],
function(val) {
return val.age === 23;
}
); // -> {name: 'jane', age: 23}
Return the first index where the predicate truth test passes.
function findIdx(arr: any[], predicate: types.AnyFn): number;
Name | Desc |
---|---|
arr | Array to search |
predicate | Function invoked per iteration |
return | 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.
function findKey(
obj: any,
predicate: types.AnyFn,
ctx?: any
): string | void;
Name | Desc |
---|---|
obj | Object to search |
predicate | Function invoked per iteration |
ctx | Predicate context |
return | 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.
function findLastIdx(arr: any[], predicate: types.AnyFn): number;
Name | Desc |
---|---|
arr | Array to search |
predicate | Function invoked per iteration |
return | 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.
function flatten(arr: any[]): any[];
Name | Desc |
---|---|
arr | Array to flatten |
return | New flattened array |
flatten(['a', ['b', ['c']], 'd', ['e']]); // -> ['a', 'b', 'c', 'd', 'e']
Validate function arguments.
function fnArgs(types: string[], args: any): void;
Name | Desc |
---|---|
types | Argument types |
args | Argument object |
It throws an exception when validation failed.
function test(a, b, c) {
fnArgs(['number|string', '?Function', '...number'], arguments);
// Do something.
}
test(15);
test('test', () => {});
test('test', () => {}, 5);
test(); // Throw error
test('test', 'test'); // Throw error
test('test', () => {}, 5, 'test'); // Throw error
Get a function parameter's names.
function fnParams(fn: types.AnyFn | string): string[];
Name | Desc |
---|---|
fn | Function to get parameters |
return | Names |
fnParams(function(a, b) {}); // -> ['a', 'b']
Simple FNV-1a implementation.
function fnv1a(str: string): number;
Name | Desc |
---|---|
str | String to hash |
return | Hast result |
fnv1a('test'); // -> 2949673445
Format string in a printf-like format.
function format(str: string, ...values: any[]): string;
Name | Desc |
---|---|
str | String to format |
...values | Values to replace format specifiers |
return | 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.
function fraction(num: number): string;
Name | Desc |
---|---|
num | Number to convert |
return | Corresponding fraction |
fraction(1.2); // -> '6/5'
Shortcut for Object.freeze.
function freeze<T>(obj: T): T;
Use Object.defineProperties if Object.freeze is not supported.
Name | Desc |
---|---|
obj | Object to freeze |
return | Object passed in |
const a = { b: 1 };
freeze(a);
a.b = 2;
console.log(a); // -> {b: 1}
Recursively use Object.freeze.
function freezeDeep<T>(obj: T): T;
Name | Desc |
---|---|
obj | Object to freeze |
return | Object passed in |
const a = { b: { c: 1 } };
freezeDeep(a);
a.b.c = 2;
console.log(a); // -> {b: {c: 1}}
Promised version of node.js fs module.
const fs: {
readFile(path: string, encoding: string): Promise<string>;
readFile(path: string): Promise<Buffer>;
exists(path: string): Promise<boolean>;
unlink(path: string): Promise<void>;
writeFile(path: string, data: string, options?: string): Promise<void>;
writeFile(path: string, data: Buffer): Promise<void>;
readdir(path: string): Promise<string[]>;
rmdir(path: string): Promise<void>;
[key: string]: any;
};
fs.readFile('test.js')
.then(function(data) {
// Do something
})
.catch(function(err) {
// Handle errors
});
Fullscreen api wrapper.
namespace fullscreen {
interface IFullscreen extends Emitter {
request(el?: Element): void;
exit(): void;
toggle(el?: Element): void;
isActive(): boolean;
getEl(): Element | null;
isEnabled(): boolean;
}
}
const fullscreen: fullscreen.IFullscreen;
Request fullscreen.
Name | Desc |
---|---|
el | Fullscreen element |
Exit fullscreen.
Toggle fullscreen.
Name | Desc |
---|---|
el | Fullscreen element |
Check Whether fullscreen is active.
Return Fullscreen element if exists.
Whether you are allowed to enter fullscreen.
fullscreen.request();
fullscreen.isActive(); // -> false, not a synchronous api
fullscreen.on('error', () => {});
fullscreen.on('change', () => {});
Simple fuzzy search.
function fuzzySearch(
needle: string,
haystack: any[],
options?: {
caseSensitive?: boolean;
key?: string | string[];
}
): any[];
Name | Desc |
---|---|
needle | String to search |
haystacks | Search list |
options | Search options |
Available options:
Name | Desc |
---|---|
caseSensitive=false | Whether comparisons should be case sensitive |
key | Object key path if item is object |
fuzzySearch('lic', ['licia', 'll', 'lic']); // -> ['lic', 'licia']
fuzzySearch(
'alpha-test',
[
{
name: 'alpha-test-1'
},
{
name: 'beta-test'
}
],
{
key: 'name'
}
); // -> [{ name: 'alpha-test-1' }]
Compute the greatest common divisor using Euclid's algorithm.
function gcd(a: number, b: number): number;
Name | Desc |
---|---|
a | Number to calculate |
b | Number to calculate |
return | Greatest common divisor |
gcd(121, 44); // -> 11
Get an available TCP port.
function getPort(
port?: number | number[],
host?: string
): Promise<number>;
Name | Desc |
---|---|
port | Preferred ports |
host | Host address |
return | Available port |
If preferred ports are not available, a random port will be returned.
getPort([3000, 3001], '127.0.0.1').then(port => {
console.log(port);
});
Get prototype of an object.
function getProto(obj: any): any;
Name | Desc |
---|---|
obj | Target object |
return | Prototype of given object, null if not exists |
const a = {};
getProto(Object.create(a)); // -> a
Get url param.
function getUrlParam(
name: string,
url?: string
): string | undefined;
Name | Desc |
---|---|
name | Param name |
url=location | Url to get param |
return | Param value |
getUrlParam('test', 'http://example.com/?test=true'); // -> 'true'
Handle errors like golang.
function golangify<T, U = Error>(
fn: (...args: any[]) => Promise<T>
): (...args: any[]) => Promise<[T | undefined, U | null]>;
function golangify<T, U = Error>(
p: Promise<T>
): Promise<[T | undefined, U | null]>;
Name | Desc |
---|---|
fn | Function that returns a Promise |
return | Like fn, but resolves with [result, error] |
Name | Desc |
---|---|
p | Promise to transform |
return | Promise that resolves with [result, error] |
(async () => {
let fnA = golangify(async () => {
throw Error('err');
});
await fnA(); // -> [undefined, Error]
let fnB = golangify(async num => num * 2);
await fnB(2); // -> [4, null]
await golangify(Promise.reject(Error('err'))); // -> [undefined, Error]
await golangify(Promise.resolve(4)); // -> [4, null]
})();
Create html with JavaScript.
function h(
tag: string,
attrs?: types.PlainObj<any>,
...child: Array<string | HTMLElement>
): HTMLElement;
Name | Desc |
---|---|
tag | Tag name |
attrs | Attributes |
...child | Children |
return | Created element |
const el = h(
'div#test.title',
{
onclick: function() {},
title: 'test'
},
'inner text'
);
document.body.appendChild(el);
Checks if key is a direct property.
function has(obj: {}, key: string): boolean;
Name | Desc |
---|---|
obj | Object to query |
key | Path to check |
return | True if key is a direct property |
has({ one: 1 }, 'one'); // -> true
Heap sort implementation.
function heapSort(arr: any[], cmp?: types.AnyFn): any[];
Name | Desc |
---|---|
arr | Array to sort |
cmp | Comparator |
return | Sorted array |
heapSort([2, 1]); // -> [1, 2]
Hex encoding and decoding.
const hex: {
encode(bytes: number[]): string;
decode(str: string): number[];
};
Turn a byte array into a hex string.
Name | Desc |
---|---|
bytes | Byte array |
return | hex string |
Turn a hex string into a byte array.
Name | Desc |
---|---|
str | hex string |
return | Byte array |
hex.encode([168, 174, 155, 255]); // -> 'a8ae9bff'
hex.decode('a8ae9bff'); // -> [168, 174, 155, 255]
Highlight code.
function highlight(
str: string,
lang?: string,
style?: {
comment?: string;
string?: string;
number?: string;
keyword?: string;
operator?: string;
}
): string;
Name | Desc |
---|---|
str | Code string |
lang=js | Language, js, html or css |
style | Keyword highlight style |
return | Highlighted html code string |
Available styles:
comment, string, number, keyword, operator
highlight('const a = 5;', 'js', {
keyword: 'color:#569cd6;'
}); // -> '<span class="keyword" style="color:#569cd6;">const</span> a <span class="operator" style="color:#994500;">=</span> <span class="number" style="color:#0086b3;">5</span>;'
Monitor, change function arguments and result.
function hookFn<T>(
fn: T,
options: {
before?: types.AnyFn;
after?: types.AnyFn;
error?: types.AnyFn;
}
): T;
Name | Desc |
---|---|
fn | Function to hook |
options | Hook options |
return | Hooked function |
Available options:
Name | Desc |
---|---|
before | Arguments handler |
after | Result handler |
error | Error handler |
let sum = function(a, b) {
if (a > 100) {
throw Error('a is bigger than 100');
}
return a + b;
};
let totalSum = 0;
sum = hookFn(sum, {
before(a, b) {
return [+a, +b];
},
after(result) {
totalSum += result;
return totalSum;
},
error() {
return totalSum;
}
});
sum('2', '5'); // -> 7
Capture keyboard input to trigger given events.
const hotkey: {
on(key: string, listener: types.AnyFn): void;
off(key: string, listener: types.AnyFn): void;
};
Register keyboard listener.
Name | Desc |
---|---|
key | Key string |
listener | 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.
function hslToRgb(hsl: number[]): number[];
Name | Desc |
---|---|
hsl | Hsl values |
return | Rgb values |
hslToRgb([165, 59, 50, 0.8]); // -> [52, 203, 165, 0.8]
Html parser and serializer.
const html: {
parse(html: string): any[];
stringify(tree: any[]): string;
};
Parse html string into js object.
Name | Desc |
---|---|
html | Html string |
return | Parsed js object |
Stringify object into an html string.
Name | Desc |
---|---|
tree | Object to stringify |
return | Html string |
const tree = html.parse('<div id="name">licia</div>');
// -> [{tag: 'div', attrs: {id: 'name'}, content: ['licia']}]
html.stringify(tree);
Return the first argument given.
function identity<T>(val: T): T;
Name | Desc |
---|---|
val | Any value |
return | Given value |
identity('a'); // -> 'a'
Get the index at which the first occurrence of value.
function idxOf(arr: any[], val: any, fromIdx?: number): number;
Name | Desc |
---|---|
arr | Array to search |
val | Value to search for |
fromIdx=0 | Index to search from |
return | Value index |
idxOf([1, 2, 1, 2], 2, 2); // -> 3
Indent each line in a string.
function indent(
str: string,
char?: string,
len?: number
): string;
Name | Desc |
---|---|
str | String to indent |
char | Character to prepend |
len | Indent length |
return | Indented string |
indent('foo\nbar', ' ', 4); // -> ' foo\n bar'
Inherit the prototype methods from one constructor into another.
function inherits(
Class: types.AnyFn,
SuperClass: types.AnyFn
): void;
Name | Desc |
---|---|
Class | Child Class |
SuperClass | Super Class |
function People(name) {
this._name = name;
}
People.prototype = {
getName: function() {
return this._name;
}
};
function Student(name) {
this._name = name;
}
inherits(Student, People);
const s = new Student('RedHood');
s.getName(); // -> 'RedHood'
Ini parser and serializer.
const ini: {
parse(ini: string): any;
stringify(
obj: any,
options?: {
section?: string;
whitespace: boolean;
}
): string;
};
Parse ini string into js object.
Name | Desc |
---|---|
ini | Ini string |
return | Parsed js object |
Stringify object into an ini formatted string.
Name | Desc |
---|---|
obj | Object to stringify |
options | Stringify options |
return | Ini formatted string |
Options:
Name | Desc |
---|---|
section | Top section |
whitespace=false | Whitespace around = |
const config = ini.parse(`
; This is a comment
library = licia
[user.info]
name = surunzi
alias[] = redhoodsu
alias[] = red
`); // -> {library: 'licia', user: {info: {name: 'surunzi', alias: ['redhoodsu', 'red']}}}
ini.stringify(config);
Insertion sort implementation.
function insertionSort(arr: any[], cmp?: types.AnyFn): any[];
Name | Desc |
---|---|
arr | Array to sort |
cmp | Comparator |
return | Sorted array |
insertionSort([2, 1]); // -> [1, 2]
Compute the list of values that are the intersection of all the arrays.
function intersect(...arr: Array<any[]>): any[];
Name | Desc |
---|---|
...arr | Arrays to inspect |
return | New array of inspecting values |
intersect([1, 2, 3, 4], [2, 1, 10], [2, 1]); // -> [1, 2]
Intersect two ranges.
namespace intersectRange {
interface IRange {
start: number;
end: number;
}
}
function intersectRange(
a: intersectRange.IRange,
b: intersectRange.IRange
): intersectRange.IRange | void;
Name | Desc |
---|---|
a | Range a |
b | Range b |
return | 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
Facebook's invariant.
function invariant(
condition: boolean,
format?: string,
a?: string,
b?: string,
c?: string,
d?: string,
e?: string,
f?: string
): void;
invariant(true, 'This will not throw');
// No errors
invariant(false, 'This will throw an error with this message');
// Error: Invariant Violation: This will throw an error with this message
Create an object composed of the inverted keys and values of object.
function invert(obj: any): any;
Name | Desc |
---|---|
obj | Object to invert |
return | New inverted object |
If object contains duplicate values, subsequent values overwrite property assignments of previous values.
invert({ a: 'b', c: 'd', e: 'f' }); // -> {b: 'a', d: 'c', f: 'e'}
Check if an url is absolute.
function isAbsoluteUrl(url: string): boolean;
Name | Desc |
---|---|
url | Url to check |
return | 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.
function isArgs(val: any): val is IArguments;
Name | Desc |
---|---|
val | Value to check |
return | True if value is an arguments object |
isArgs(
(function() {
return arguments;
})()
); // -> true
Check if value is an Array
object.
function isArr(val: any): val is any[];
Name | Desc |
---|---|
val | Value to check |
return | True if value is an Array object |
isArr([]); // -> true
isArr({}); // -> false
Check if value is an ArrayBuffer.
function isArrBuffer(val: any): val is ArrayBuffer;
Name | Desc |
---|---|
val | Value to check |
return | True if value is an ArrayBuffer |
isArrBuffer(new ArrayBuffer(8)); // -> true
Check if value is array-like.
function isArrLike(val: any): boolean;
Name | Desc |
---|---|
val | Value to check |
return | 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 an async function.
function isAsyncFn(val: any): boolean;
Name | Desc |
---|---|
val | Value to check |
return | True if value is an async function |
isAsyncFn(function*() {}); // -> false
isAsyncFn(function() {}); // -> false
isAsyncFn(async function() {}); // -> true
Check if value is a Blob.
function isBlob(val: any): boolean;
Name | Desc |
---|---|
val | Value to check |
return | True if value is a Blob |
isBlob(new Blob([])); // -> true;
isBlob([]); // -> false
Check if value is a boolean primitive.
function isBool(val: any): val is boolean;
Name | Desc |
---|---|
val | Value to check |
return | True if value is a boolean |
isBool(true); // -> true
isBool(false); // -> true
isBool(1); // -> false
Check if running in a browser.
const isBrowser: boolean;
console.log(isBrowser); // -> true if running in a browser
Check if value is a buffer.
function isBuffer(val: any): boolean;
Name | Desc |
---|---|
val | The value to check |
return | True if value is a buffer |
isBuffer(new Buffer(4)); // -> true
Check if values are close(almost equal) to each other.
function isClose(
a: number,
b: number,
relTol?: number,
absTol?: number
): boolean;
abs(a-b) <= max(relTol * max(abs(a), abs(b)), absTol)
Name | Desc |
---|---|
a | Number to compare |
b | Number to compare |
relTol=1e-9 | Relative tolerance |
absTol=0 | Absolute tolerance |
return | 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
Detect cyclic object reference.
function isCyclic(val: any): boolean;
Name | Desc |
---|---|
val | Value to detect |
return | True if value is cyclic |
isCyclic({}); // -> false
const obj = { a: 1 };
obj.b = obj;
isCyclic(obj); // -> true
Detect dark mode.
function isDarkMode(): boolean;
console.log(isDarkMode()); // true if dark mode
Check if a string is a valid data url.
function isDataUrl(str: string): boolean;
Name | Desc |
---|---|
str | String to check |
return | 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.
function isDate(val: any): boolean;
Name | Desc |
---|---|
val | value to check |
return | True if value is a Date object |
isDate(new Date()); // -> true
Check if a path is directory.
function isDir(path: string): Promise<boolean>;
Name | Desc |
---|---|
path | Path to check |
return | True if path is a directory |
isDir('/foo/bar');
Check if the process is running inside a docker container.
function isDocker(): boolean;
console.log(isDocker()); // -> true if running inside a docker container.
Check if value is a DOM element.
function isEl(val: any): val is Element;
Name | Desc |
---|---|
val | Value to check |
return | True if value is a DOM element |
isEl(document.body); // -> true
Loosely validate an email address.
function isEmail(val: string): boolean;
Name | Desc |
---|---|
val | Value to check |
return | True if value is an email like string |
isEmail('surunzi@foxmail.com'); // -> true
Check if value is an empty object or array.
function isEmpty(val: any): boolean;
Name | Desc |
---|---|
val | Value to check |
return | 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.
function isEqual(val: any, other: any): boolean;
Name | Desc |
---|---|
val | Value to compare |
other | Other value to compare |
return | True if values are equivalent |
isEqual([1, 2, 3], [1, 2, 3]); // -> true
Check if value is an error.
function isErr(val: any): val is Error;
Name | Desc |
---|---|
val | Value to check |
return | True if value is an error |
isErr(new Error()); // -> true
Check if number is even.
function isEven(num: number): boolean;
Name | Desc |
---|---|
num | Number to check |
return | True if number is even |
isEven(0); // -> true
isEven(1); // -> false
isEven(2); // -> true
Check if value is a file.
function isFile(val: any): boolean;
Name | Desc |
---|---|
val | Value to check |
return | True if value is a file |
isFile(new File(['test'], 'test.txt', { type: 'text/plain' })); // -> true
Check if value is a finite primitive number.
function isFinite(val: any): boolean;
Name | Desc |
---|---|
val | Value to check |
return | True if value is a finite number |
isFinite(3); // -> true
isFinite(Infinity); // -> false
Check if value is a function.
function isFn(val: any): val is Function;
Name | Desc |
---|---|
val | Value to check |
return | True if value is a function |
Generator function is also classified as true.
isFn(function() {}); // -> true
isFn(function*() {}); // -> true
isFn(async function() {}); // -> true
Check if character is full width.
function isFullWidth(codePoint: number): boolean;
Name | Desc |
---|---|
codePoint | Unicode code point |
return | True if character is full width |
isFullWidth('a'.codePointAt(0)); // -> false
isFullWidth(','.codePointAt(0)); // -> false
isFullWidth('我'.codePointAt(0)); // -> true
isFullWidth(','.codePointAt(0)); // -> true
Check if value is a generator function.
function isGeneratorFn(val: any): boolean;
Name | Desc |
---|---|
val | Value to check |
return | True if value is a generator function |
isGeneratorFn(function*() {}); // -> true
isGeneratorFn(function() {}); // -> false
Check if element is hidden.
function isHidden(
el: Element,
options?: {
display?: boolean;
visibility?: boolean;
opacity?: boolean;
size?: boolean;
viewport?: boolean;
overflow?: boolean;
}
): boolean;
Name | Desc |
---|---|
el | Target element |
options | Check options |
return | True if element is hidden |
Available options:
Name | Desc |
---|---|
display=true | Check if it is displayed |
visibility=false | Check visibility css property |
opacity=false | Check opacity css property |
size=false | Check width and height |
viewport=false | Check if it is in viewport |
overflow=false | Check if hidden in overflow |
isHidden(document.createElement('div')); // -> true
Checks if value is classified as a Integer.
function isInt(val: any): boolean;
Name | Desc |
---|---|
val | Value to check |
return | True if value is correctly classified |
isInt(5); // -> true
isInt(5.1); // -> false
isInt({}); // -> false
Check if value is an IP address.
namespace isIp {
function v4(str: string): boolean;
function v6(str: string): boolean;
}
function isIp(str: string): boolean;
Name | Desc |
---|---|
str | String to check |
return | True if value is an IP address |
Check if value is an IPv4 address.
Check if value is an IPv6 address.
isIp('192.168.191.1'); // -> true
isIp('1:2:3:4:5:6:7:8'); // -> true
isIp('test'); // -> false
isIp.v4('192.168.191.1'); // -> true
isIp.v6('1:2:3:4:5:6:7:8'); // -> true
Check if value is a valid JSON.
function isJson(val: string): boolean;
It uses JSON.parse()
and a try... catch
block.
Name | Desc |
---|---|
val | JSON string |
return | True if value is a valid JSON |
isJson('{"a": 5}'); // -> true
isJson("{'a': 5}"); // -> false
Check if a year is a leap year.
function isLeapYear(year: number): boolean;
Name | Desc |
---|---|
year | Year to check |
return | True if year is a leap year |
isLeapYear(2000); // -> true
isLeapYear(2002); // -> false
Check if value is a Map object.
function isMap(val: any): boolean;
Name | Desc |
---|---|
val | Value to check |
return | True if value is a Map |
isMap(new Map()); // -> true
isMap(new WeakMap()); // -> false
Check if keys and values in src are contained in obj.
function isMatch(obj: any, src: any): boolean;
Name | Desc |
---|---|
obj | Object to inspect |
src | Object of property values to match |
return | True if object is match |
isMatch({ a: 1, b: 2 }, { a: 1 }); // -> true
Check if running in wechat mini program.
const isMiniProgram: boolean;
console.log(isMiniProgram); // -> true if running in mini program.
Check whether client is using a mobile browser using ua.
function isMobile(ua?: string): boolean;
Name | Desc |
---|---|
ua=navigator.userAgent | User agent |
return | True if ua belongs to mobile browsers |
isMobile(navigator.userAgent);
Check if value is an NaN.
function isNaN(val: any): boolean;
Name | Desc |
---|---|
val | Value to check |
return | 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.
function isNative(val: any): boolean;
Name | Desc |
---|---|
val | Value to check |
return | 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.
function isNil(val: any): boolean;
Name | Desc |
---|---|
val | Value to check |
return | 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.
const isNode: boolean;
console.log(isNode); // -> true if running in node
Check if value is an Null.
function isNull(val: any): val is null;
Name | Desc |
---|---|
val | Value to check |
return | True if value is an Null |
isNull(null); // -> true
Check if value is classified as a Number primitive or object.
function isNum(val: any): val is number;
Name | Desc |
---|---|
val | Value to check |
return | True if value is correctly classified |
isNum(5); // -> true
isNum(5.1); // -> true
isNum({}); // -> false
Check if value is numeric.
function isNumeric(val: any): boolean;
Name | Desc |
---|---|
val | Value to check |
return | True if value is numeric |
isNumeric(1); // -> true
isNumeric('1'); // -> true
isNumeric(Number.MAX_VALUE); // -> true
isNumeric(0xff); // -> true
isNumeric(''); // -> false
isNumeric('1.1.1'); // -> false
isNumeric(NaN); // -> false
Check if value is the language type of Object.
function isObj(val: any): boolean;
Name | Desc |
---|---|
val | Value to check |
return | True if value is an object |
isObj({}); // -> true
isObj([]); // -> true
Check if number is odd.
function isOdd(num: number): boolean;
Name | Desc |
---|---|
num | Number to check |
return | True if number is odd |
isOdd(0); // -> false
isOdd(1); // -> true
isOdd(2); // -> false
Check if value is an object created by Object constructor.
function isPlainObj(val: any): boolean;
Name | Desc |
---|---|
val | Value to check |
return | True if value is a plain object |
isPlainObj({}); // -> true
isPlainObj([]); // -> false
isPlainObj(function() {}); // -> false
Check if a TCP port is free.
function isPortFree(
port: number,
host?: string
): Promise<boolean>;
Name | Desc |
---|---|
port | TCP port |
host | Host address |
return | True if given port is free |
isPortFree(3000).then(isFree => {
// Do something.
});
Check if the provided integer is a prime number.
function isPrime(num: number): boolean;
Name | Desc |
---|---|
num | Number to check |
return | True if number is a prime number |
isPrime(11); // -> true
isPrime(8); // -> false
Check if value is string, number, boolean or null.
function isPrimitive(val: any): boolean;
Name | Desc |
---|---|
val | Value to check |
return | True if value is a primitive |
isPrimitive(5); // -> true
isPrimitive('abc'); // -> true
isPrimitive(false); // -> true
Check if value looks like a promise.
function isPromise(val: any): boolean;
Name | Desc |
---|---|
val | Value to check |
return | True if value looks like a promise |
isPromise(new Promise(function() {})); // -> true
isPromise({}); // -> false
Check if value is a regular expression.
function isRegExp(val: any): val is RegExp;
Name | Desc |
---|---|
val | Value to check |
return | True if value is a regular expression |
isRegExp(/a/); // -> true
Check if path appears to be relative.
function isRelative(path: string): boolean;
Name | Desc |
---|---|
path | Path to check |
return | True if path appears to be relative |
isRelative('README.md'); // -> true
Determine if running on a high DPR device or not.
const isRetina: boolean;
console.log(isRetina); // -> true if high DPR
Check if process is running.
function isRunning(pid: number): boolean;
Name | Desc |
---|---|
pid | Process id |
return | True if process is running |
isRunning(123456); // true if running
Check if value is a Set object.
function isSet(val: any): boolean;
Name | Desc |
---|---|
val | Value to check |
return | True if value is a Set |
isSet(new Set()); // -> true
isSet(new WeakSet()); // -> false
Check if an array is sorted.
function isSorted(arr: any[], cmp?: types.AnyFn): boolean;
Name | Desc |
---|---|
arr | Array to check |
cmp | Comparator |
return | True if array is sorted |
isSorted([1, 2, 3]); // -> true
isSorted([3, 2, 1]); // -> false
Check if value is a string primitive.
function isStr(val: any): val is string;
Name | Desc |
---|---|
val | Value to check |
return | True if value is a string primitive |
isStr('licia'); // -> true
Check if string is blank.
function isStrBlank(str: string): boolean;
Name | Desc |
---|---|
str | String to check |
return | True if string is blank |
isStrBlank('licia'); // -> false
isStrBlank(''); // -> true
isStrBlank(' '); // -> true
isStrBlank('\r\n '); // -> true
Check if value is a Node.js stream.
function isStream(val: any): boolean;
Name | Desc |
---|---|
val | Value to check |
return | True if value is a Node.js stream |
const stream = require('stream');
isStream(new stream.Stream()); // -> true
Check if value is a symbol.
function isSymbol(val: any): val is symbol;
Name | Desc |
---|---|
val | Value to check |
return | True if value is a symbol |
isSymbol(Symbol('test')); // -> true
Check if value is a typed array.
function isTypedArr(val: any): boolean;
Name | Desc |
---|---|
val | Value to check |
return | True if value is a typed array |
isTypedArr([]); // -> false
isTypedArr(new Uint8Array(8)); // -> true
Check if value is undefined.
function isUndef(val: any): val is undefined;
Name | Desc |
---|---|
val | Value to check |
return | True if value is undefined |
isUndef(void 0); // -> true
isUndef(null); // -> false
Loosely validate an url.
function isUrl(val: string): boolean;
Name | Desc |
---|---|
val | Value to check |
return | True if value is an url like string |
isUrl('http://www.example.com?foo=bar¶m=test'); // -> true
Check if value is a WeakMap object.
function isWeakMap(val: any): boolean;
Name | Desc |
---|---|
val | Value to check |
return | True if value is a WeakMap |
isWeakMap(new Map()); // -> false
isWeakMap(new WeakMap()); // -> true
Check if value is a WeakSet object.
function isWeakSet(val: any): boolean;
Name | Desc |
---|---|
val | Value to check |
return | True if value is a WeakSet |
isWeakSet(new Set()); // -> false
isWeakSet(new WeakSet()); // -> true
Check if platform is windows.
const isWindows: boolean;
console.log(isWindows); // -> true if running on windows
Use JSON parse and stringify to clone object.
function jsonClone<T>(val: T): T;
Name | Desc |
---|---|
val | Value to clone |
return | Cloned value |
jsonClone({ name: 'licia' }); // -> { name: 'licia' }
A simple jsonp implementation.
function jsonp(options: {
url: string;
data?: any;
success?: types.AnyFn;
param?: string;
name?: string;
error?: types.AnyFn;
complete?: types.AnyFn;
timeout?: number;
}): void;
Name | Desc |
---|---|
options | Jsonp Options |
Available options:
Name | Desc |
---|---|
url | Request url |
data | Request data |
success | Success callback |
param=callback | Callback param |
name | Callback name |
error | Error callback |
complete | Callback after request |
timeout | Request timeout |
jsonp({
url: 'http://example.com',
data: { test: 'true' },
success: function(data) {
// ...
}
});
Convert string to "kebabCase".
function kebabCase(str: string): string;
Name | Desc |
---|---|
str | String to convert |
return | 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.
function keyCode(name: string): number;
function keyCode(code: number): string;
Get key code's name.
Name | Desc |
---|---|
code | Key code |
return | Corresponding key name |
Get key name's code.
Name | Desc |
---|---|
name | Key name |
return | Corresponding key code |
keyCode(13); // -> 'enter'
keyCode('enter'); // -> 13
Create an array of the own enumerable property names of object.
function keys(obj: any): string[];
Name | Desc |
---|---|
obj | Object to query |
return | Array of property names |
keys({ a: 1 }); // -> ['a']
Kill process.
function kill(pid: number): void;
Name | Desc |
---|---|
pid | Process ID |
kill(9420);
Get the last element of array.
function last(arr: any[]): any;
Name | Desc |
---|---|
arr | The array to query |
return | The last element of array |
last([1, 2]); // -> 2
Import modules lazily, Proxy is used.
function lazyImport<T>(
importFn: (moduleId: string) => T,
dirname?: string
): (moduleId: string) => T;
Name | Desc |
---|---|
importFn | Actual function to require module |
dirname | Current file folder |
return | New function to require module |
const r = lazyImport(require);
const _ = r('underscore');
_.isNumber(5);
Require modules lazily.
function lazyRequire<T>(
requireFn: (moduleId: string) => T
): (moduleId: string) => T;
const r = lazyRequire(require);
const _ = r('underscore');
// underscore is required only when _ is called.
_().isNumber(5);
Levenshtein distance implementation.
function levenshtein(a: string, b: string): number;
Name | Desc |
---|---|
a | First string |
b | Second string |
return | Levenshtein distance between a and b |
levenshtein('cat', 'cake'); // -> 2
Hyperlink urls in a string.
function linkify(str: string, hyperlink?: types.AnyFn): string;
Name | Desc |
---|---|
str | String to hyperlink |
hyperlink | Function to hyperlink url |
return | Result string |
const str = 'Official site: http://eustia.liriliri.io';
linkify(str); // -> 'Official site: <a href="http://eustia.liriliri.io">http://eustia.liriliri.io</a>'
linkify(str, function(url) {
return '<a href="' + url + '" target="_blank">' + url + '</a>';
});
Inject link tag into page with given href value.
function loadCss(src: string, cb?: types.AnyFn): void;
Name | Desc |
---|---|
src | Style source |
cb | Onload callback |
loadCss('style.css', function(isLoaded) {
// Do something...
});
Load image with given src.
function loadImg(src: string, cb?: types.AnyFn): void;
Name | Desc |
---|---|
src | Image source |
cb | 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.
function loadJs(src: string, cb?: types.AnyFn): void;
Name | Desc |
---|---|
src | Script source |
cb | Onload callback |
loadJs('main.js', function(isLoaded) {
// Do something...
});
Get the longest item in an array.
function longest(arr: string[]): string;
Name | Desc |
---|---|
arr | Array to inspect |
return | Longest item |
longest(['a', 'abcde', 'abc']); // -> 'abcde'
Convert string to lower case.
function lowerCase(str: string): string;
Name | Desc |
---|---|
str | String to convert |
return | Lower cased string |
lowerCase('TEST'); // -> 'test'
Pad string on the left side if it's shorter than length.
function lpad(str: string, len: number, chars?: string): string;
Name | Desc |
---|---|
str | String to pad |
len | Padding length |
chars | String used as padding |
return | Result 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.
function ltrim(str: string, chars?: string | string[]): string;
Name | Desc |
---|---|
str | String to trim |
chars | Characters to trim |
return | 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.
function map<T, TResult>(
list: types.List<T>,
iterator: types.ListIterator<T, TResult>,
context?: any
): TResult[];
function map<T, TResult>(
object: types.Dictionary<T>,
iterator: types.ObjectIterator<T, TResult>,
context?: any
): TResult[];
Name | Desc |
---|---|
object | Collection to iterate over |
iterator | Function invoked per iteration |
context | Function context |
return | New mapped array |
map([4, 8], function(n) {
return n * n;
}); // -> [16, 64]
Map for objects.
function mapObj<T, TResult>(
object: types.Dictionary<T>,
iterator: types.ObjectIterator<T, TResult>,
context?: any
): types.Dictionary<TResult>;
Name | Desc |
---|---|
object | Object to iterate over |
iterator | Function invoked per iteration |
context | Function context |
return | 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.
function matcher(attrs: any): types.AnyFn;
Name | Desc |
---|---|
attrs | Object of property values to match |
return | New predicate function |
const filter = require('licia/filter');
const objects = [
{ a: 1, b: 2, c: 3 },
{ a: 4, b: 5, c: 6 }
];
filter(objects, matcher({ a: 4, c: 6 })); // -> [{a: 4, b: 5, c: 6}]
Get maximum value of given numbers.
function max(...num: number[]): number;
Name | Desc |
---|---|
...num | Numbers to calculate |
return | Maximum value |
max(2.3, 1, 4.5, 2); // 4.5
MD5 implementation.
function md5(msg: string | number[]): string;
Name | Desc |
---|---|
msg | Message to encrypt |
return | MD5 hash |
md5('licia'); // -> 'e59f337d85e9a467f1783fab282a41d0'
Memory-backed implementation of the Web Storage API.
const memStorage: typeof window.localStorage;
A replacement for environments where localStorage or sessionStorage is not available.
const localStorage = window.localStorage || memStorage;
localStorage.setItem('test', 'licia');
Memoize a given function by caching the computed result.
function memoize(
fn: types.AnyFn,
hashFn?: types.AnyFn
): types.AnyFn;
Name | Desc |
---|---|
fn | Function to have its output memoized |
hashFn | Function to create cache key |
return | New memoized function |
const fibonacci = memoize(function(n) {
return n < 2 ? n : fibonacci(n - 1) + fibonacci(n - 2);
});
Merge the contents of arrays together into the first array.
function mergeArr<T, U>(
first: ArrayLike<T>,
...arrays: ArrayLike<U>[]
): ArrayLike<T | U>;
Name | Desc |
---|---|
first | Array to merge |
arrays | Arrays to merge into the first array |
return | First array |
const a = [1, 2];
mergeArr(a, [3, 4], [5, 6]);
console.log(a); // -> [1, 2, 3, 4, 5, 6]
Merge sort implementation.
function mergeSort(arr: any[], cmp?: types.AnyFn): any[];
Note: It's not an "in-place" sort.
Name | Desc |
---|---|
arr | Array to sort |
cmp | Comparator |
return | Sorted array |
mergeSort([2, 1]); // -> [1, 2]
Document meta manipulation, turn name and content into key value pairs.
namespace meta {
function remove(nameList: string | string[]): void;
}
function meta(): {};
function meta(key: string): string;
function meta(keys: string[]): {};
function meta(key, value): void;
function meta(pairs: {}): void;
Get meta content with given name. If name is omitted, all pairs will be return.
Name | Desc |
---|---|
name | Meta name |
return | Meta content |
Set meta content.
Name | Desc |
---|---|
name | Meta name |
content | Meta content |
Name | Desc |
---|---|
metas | Object of name content pairs |
Remove metas.
Name | Desc |
---|---|
name | 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.
function methods(obj: any): string[];
Name | Desc |
---|---|
obj | Object to check |
return | Function names in object |
methods(console); // -> ['Console', 'assert', 'dir', ...]
Common mime types.
function mime(name: string): string | undefined;
Name | Desc |
---|---|
name | Extension |
return | Mime type |
Name | Desc |
---|---|
name | Mime type |
return | Extension |
It contains only the most common file types.
mime('jpg'); // -> 'image/jpeg'
mime('bmp'); // -> 'image/bmp'
mime('video/mp4'); // -> 'mp4'
mime('test'); // -> undefined
Get minimum value of given numbers.
function min(...num: number[]): number;
Name | Desc |
---|---|
...num | Numbers to calculate |
return | Minimum value |
min(2.3, 1, 4.5, 2); // 1
Recursively create directories.
namespace mkdir {
function sync(dir: string, mode?: number): void;
}
function mkdir(
dir: string,
mode?: number,
cb?: types.AnyFn
): void;
function mkdir(dir: string, cb?: types.AnyFn): void;
Name | Desc |
---|---|
dir | Directory to create |
mode=0777 | Directory mode |
cb | Callback |
Synchronous version.
mkdir('/tmp/foo/bar/baz', function(err) {
if (err) console.log(err);
else console.log('Done');
});
mkdir.sync('/tmp/foo2/bar/baz');
Tiny moment.js like implementation.
namespace moment {
class M {
constructor(value: string | Date);
format(mask: string): string;
isValid(): boolean;
isLeapYear(): boolean;
isSame(that: M): boolean;
valueOf(): number;
isBefore(that: M): boolean;
isAfter(that: M): boolean;
year(): number;
year(number): M;
month(): number;
month(number): M;
date(): number;
date(number): M;
hour(): number;
hour(number): M;
minute(): number;
minute(number): M;
second(): number;
second(number): M;
millisecond(): number;
millisecond(number): M;
unix(): number;
clone(): M;
toDate(): Date;
toArray(): number[];
toJSON(): string;
toISOString(): string;
toObject(): any;
toString(): string;
set(unit: string, num: number): M;
startOf(unit: string): M;
endOf(unit: string): M;
daysInMonth(): number;
add(num: number, unit: string): M;
subtract(num: number, unit: string): M;
diff(input: M | string | Date, unit: string, asFloat: boolean): number;
}
}
function moment(value: string | Date): moment.M;
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'
Morph a dom tree to match a target dom tree.
function morphDom(from: Node, to: Node | string): Node;
Name | Type |
---|---|
from | Node to morph |
to | Node to be morphed |
return | Morphed node |
const el1 = document.createElement('div');
el1.className = 'test';
const el2 = document.createElement('div');
el2.className = 'licia';
morphDom(el1, el2);
console.log(el1.className); // -> 'licia'
Morse code encoding and decoding.
const morse: {
encode(txt: string): string;
decode(morse: string): string;
};
Turn text into Morse code.
Name | Desc |
---|---|
txt | Text to encode |
return | Morse code |
Decode Morse code into text.
Name | Desc |
---|---|
morse | Morse code |
return | Decoded string |
const str = morse.encode('Hello, world.');
// -> '.... . .-.. .-.. --- --..-- ....... .-- --- .-. .-.. -.. .-.-.-'
morse.decode(str); // -> 'Hello, world.'
Convert time string formats to milliseconds.
function ms(str: string): number;
function ms(num: number): string;
Turn time string into milliseconds.
Name | Desc |
---|---|
str | String format |
return | Milliseconds |
Turn milliseconds into time string.
Name | Desc |
---|---|
num | Milliseconds |
return | 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'
Sort values in natural order.
function naturalSort<T extends any[]>(arr: T): T;
Name | Desc |
---|---|
arr | Array of values |
return | Sorted array |
naturalSort(['img12', 'img11', '$img', '_img', '1', '2', '12']);
// -> ['1', '2', '12', '$img', 'img11', 'img12', '_img']
naturalSort([2, '1', 13]); // -> ['1', 2, 13]
Create a function that negates the result of the predicate function.
function negate<T extends types.AnyFn>(predicate: T): T;
Name | Desc |
---|---|
predicate | Predicate to negate |
return | New function |
function even(n) {
return n % 2 === 0;
}
[1, 2, 3, 4, 5, 6].filter(negate(even)); // -> [1, 3, 5]
Next tick for both node and browser.
function nextTick(cb: types.AnyFn): void;
Name | Desc |
---|---|
cb | Function to call |
Use process.nextTick if available.
Otherwise setImmediate or setTimeout is used as fallback.
nextTick(function() {
// Do something...
});
A no-operation function.
function noop(): void;
noop(); // Does nothing
Normalize http header name.
function normalizeHeader(header: string): string;
Name | Desc |
---|---|
header | Header to normalize |
return | Normalized header |
normalizeHeader('content-type'); // -> 'Content-Type'
normalizeHeader('etag'); // -> 'ETag'
Normalize file path slashes.
function normalizePath(path: string): string;
Name | Desc |
---|---|
path | Path to normalize |
return | Normalized path |
normalizePath('\\foo\\bar\\'); // -> '/foo/bar/'
normalizePath('./foo//bar'); // -> './foo/bar'
Normalize phone numbers into E.164 format.
function normalizePhone(
phone: string,
options: {
countryCode: number;
trunkPrefix?: boolean;
}
): string;
Name | Desc |
---|---|
phone | Phone to normalize |
options | Normalize options |
return | Normalized phone |
Available options:
Name | Desc |
---|---|
countryCode | Country code |
trunkPrefix=false | True if local format has trunk prefix |
normalizePhone('13512345678', {
countryCode: 86
}); // -> '+8613512345678'
normalizePhone('(415) 555-2671', {
countryCode: 1
}); // -> '+14155552671'
normalizePhone('020 7183 8750', {
countryCode: 44,
trunkPrefix: true
}); // -> '+442071838750'
Wrapper for the Web Notifications API.
namespace notify {
class Notification extends Emitter {
constructor(title: string, options?: object);
show(): void;
}
}
function notify(title: string, options?: object): void;
Name | Desc |
---|---|
title | Notification title |
options | Notification options |
You can pass exactly the same options supported in the Web Notification.
Use this to create instance when certain events like close, show, click or error needed to be handled.
notify('licia', {
body: 'This is the notification content'
});
const notification = new notify.Notification('licia', {
body: 'This is the notification content'
});
notification.on('error', err => console.log(err));
notification.on('click', e => console.log(e));
notification.show();
Gets the number of milliseconds that have elapsed since the Unix epoch.
function now(): number;
now(); // -> 1468826678701
Alias of Object.prototype.toString.
function objToStr(val: any): string;
Name | Desc |
---|---|
val | Source value |
return | String representation of given value |
objToStr(5); // -> '[object Number]'
Opposite of pick.
function omit(
obj: any,
filter: string | string[] | Function
): any;
Name | Desc |
---|---|
obj | Source object |
filter | Object filter |
return | 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}
Create a function that invokes once.
function once(fn: types.AnyFn): types.AnyFn;
Name | Desc |
---|---|
fn | Function to restrict |
return | New restricted function |
function init() {}
const initOnce = once(init);
initOnce();
initOnce(); // -> init is invoked once
Open stuff like url, files.
function open(target: string): any;
Name | Desc |
---|---|
target | Stuff to open |
return | Child process |
open('https://eustia.liriliri.io/');
Open file dialog to select file in browser.
function openFile(options?: {
accept?: string;
multiple?: boolean;
}): Promise<File[]>;
Name | Desc |
---|---|
options | Dialog options |
return | Files promise |
Available options:
Name | Desc |
---|---|
accept | File types |
multiple=false | Select multiple files or not |
openFile({ multiple: true }).then(fileList => {
console.log(fileList);
});
Used for function context binding.
function optimizeCb(
fn: types.AnyFn,
ctx: any,
argCount?: number
): types.AnyFn;
Add ordinal indicator to number.
function ordinal(num: number): string;
Name | Desc |
---|---|
num | Number to add indicator |
return | Result ordinal number |
ordinal(1); // -> '1st'
ordinal(2); // -> '2nd'
Screen orientation helper.
namespace orientation {
interface IOrientation extends Emitter {
get(): string;
}
}
const orientation: orientation.IOrientation;
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.
function pad(str: string, len: number, chars?: string): string;
Name | Desc |
---|---|
str | String to pad |
len | Padding length |
chars | String used as padding |
return | Result 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.
function pairs(obj: any): Array<any[]>;
Name | Desc |
---|---|
obj | Object to convert |
return | List of [key, value] pairs |
pairs({ a: 1, b: 2 }); // -> [['a', 1], ['b', 2]]
Run an array of functions in parallel.
function parallel(tasks: types.AnyFn[], cb?: types.AnyFn): void;
Name | Desc |
---|---|
tasks | Array of functions |
cb | 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.
function parseArgs(
args: string[],
options: {
names: any;
shorthands: any;
}
): any;
Name | Desc |
---|---|
args | Argument array |
options | Parse options |
return | Parsed result |
Name | Desc |
---|---|
names | option names |
shorthands | 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}
Simple html parser.
function parseHtml(
html: string,
handlers: {
start?: (tag: string, attrs: any, unary: boolean) => void;
end?: (tag: string) => void;
comment?: (text: string) => void;
text?: (text: string) => void;
}
): void;
Name | Desc |
---|---|
html | Html to parse |
handler | Handlers |
parseHtml('<div>licia</div>', {
start: (tag, attrs, unary) => {},
end: tag => {},
comment: text => {},
text: text => {}
});
Partially apply a function by filling in given arguments.
function partial(
fn: types.AnyFn,
...partials: any[]
): types.AnyFn;
Name | Desc |
---|---|
fn | Function to partially apply arguments to |
...partials | Arguments to be partially applied |
return | New partially applied function |
const sub5 = partial(function(a, b) {
return b - a;
}, 5);
sub5(20); // -> 15
Convert string to "pascalCase".
function pascalCase(str: string): string;
Name | Desc |
---|---|
str | String to convert |
return | 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.
function perfNow(): number;
const start = perfNow();
// Do something.
console.log(perfNow() - start);
Return a filtered copy of an object.
function pick(
object: any,
filter: string | string[] | Function
): any;
Name | Desc |
---|---|
object | Source object |
filter | Object filter |
return | 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}
Pipe all streams together.
import stream = require('stream');
function pipe(...streams: stream.Stream[]): void;
Name | Desc |
---|---|
...streams | Streams to pipe |
const fs = require('fs');
const through = require('licia/through');
pipe(
fs.createReadStream('in.txt'),
through(function(chunk, enc, cb) {
this.push(chunk);
cb();
}),
fs.createWriteStream('out.txt')
);
Extract a list of property values.
function pluck(object: any, key: string | string[]): any[];
Name | Desc |
---|---|
obj | Collection to iterate over |
key | Property path |
return | New array of specified property |
const 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.
function precision(num: number): number;
Name | Desc |
---|---|
num | Number to check |
return | Precision |
precision(1.234); // -> 3;
Fetch a given url.
function prefetch(url: string): Promise<void>;
Name | Desc |
---|---|
url | Url to prefetch |
It uses <link rel=prefetch>
if possible.
prefetch('https://eustia.liriliri.io/');
Add vendor prefixes to a CSS attribute.
namespace prefix {
function dash(name: string): string;
}
function prefix(name: string): string;
Name | Desc |
---|---|
name | Property name |
return | 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.
function promisify(
fn: types.AnyFn,
multiArgs?: boolean
): types.AnyFn;
Name | Desc |
---|---|
fn | Callback based function |
multiArgs=false | If callback has multiple success value |
return | Result function |
If multiArgs is set to true, the resulting promise will always fulfill with an array of the callback's success values.
const fs = require('fs');
const readFile = promisify(fs.readFile);
readFile('test.js', 'utf-8').then(function(data) {
// Do something with file content.
});
Return a function that will itself return the key property of any passed-in object.
function property(path: string | string[]): types.AnyFn;
Name | Desc |
---|---|
path | Path of the property to get |
return | New accessor function |
const obj = { a: { b