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
Parse and stringify data urls.
const dataUrl: {
parse(
dataUrl: string
): { data: string; mime: string; charset: string; base64: boolean } | null;
stringify(
data: any,
mime: string,
options?: { base64?: boolean; charset?: string }
): string;
};
Parse a data url.
Name | Desc |
---|---|
dataUrl | Data url string |
return | Parsed object |
Stringify an object into a data url.
Name | Desc |
---|---|
data | Data to stringify |
mime | Mime type |
options | Stringify options |
return | Data url string |
Name | Desc |
---|---|
base64=true | Whether is base64 |
charset | Charset |
dataUrl.parse('data:,Hello%2C%20World%21'); // -> {data: 'Hello, World!', mime: 'text/plain', charset: '', base64: false}
dataUrl.stringify('Hello, World!', 'text/plain'); // -> 'data:,Hello%2C%20World%21'
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