zso 中文文档教程
Zso
\$
jQuery like style dom manipulator.
Type Definition
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): $.$;
Available methods
offset, hide, show, first, last, get, eq, on, off, html, text, val, css, attr, data, rmAttr, remove, addClass, rmClass, toggleClass, hasClass, append, prepend, before, after
const $btn = $('#btn');
$btn.html('eustia');
$btn.addClass('btn');
$btn.show();
$btn.on('click', function() {
// Do something...
});
\$attr
Element attribute manipulation.
Type Definition
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
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'
});
\$class
Element class manipulations.
Type Definition
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
Add the specified class(es) to each element in the set of matched elements.
Name | Desc |
---|---|
element | Elements to manipulate |
names | Classes to add |
has
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 |
toggle
Add or remove one or more classes from each element in the set of matched elements, depending on either the class's presence or the value of the state argument.
Name | Desc |
---|---|
element | Elements to manipulate |
name | Class name to toggle |
remove
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
\$css
Element css manipulation.
Type Definition
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
\$data
Wrapper of \$attr, adds data- prefix to keys.
Type Definition
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');
\$event
bind events to certain dom elements.
Type Definition
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
Insert html on different position.
Type Definition
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;
};
before
Insert content before elements.
after
Insert content after elements.
prepend
Insert content to the beginning of elements.
append
Insert content to the end of elements.
Name | Desc |
---|---|
element | Elements to manipulate |
content | Html strings or element |
// <div id="test"><div class="mark"></div></div>
$insert.before('#test', '<div>zso</div>');
// -> <div>zso</div><div id="test"><div class="mark"></div></div>
$insert.after('#test', '<div>zso</div>');
// -> <div id="test"><div class="mark"></div></div><div>zso</div>
$insert.prepend('#test', '<div>zso</div>');
// -> <div id="test"><div>zso</div><div class="mark"></div></div>
$insert.append('#test', '<div>zso</div>');
// -> <div id="test"><div class="mark"></div><div>zso</div></div>
\$offset
Get the position of the element in document.
Type Definition
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}
\$property
Element property html, text, val getter and setter.
Type Definition
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;
};
html
Get the HTML contents of the first element in the set of matched elements or set the HTML contents of every matched element.
text
Get the combined text contents of each element in the set of matched elements, including their descendants, or set the text contents of the matched elements.
val
Get the current value of the first element in the set of matched elements or set the value of every matched element.
$property.html('#test', 'zso');
$property.html('#test'); // -> zso
\$remove
Remove the set of matched elements from the DOM.
Type Definition
function $remove(element: $safeEls.El);
Name | Desc |
---|---|
element | Elements to delete |
$remove('#test');
\$safeEls
Convert value into an array, if it's a string, do querySelector.
Type Definition
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
Show elements.
Type Definition
function $show(element: $safeEls.El): void;
Name | Desc |
---|---|
element | Elements to show |
$show('#test');
Benchmark
JavaScript Benchmark.
Type Definition
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[]>;
}
constructor
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
Run benchmark, returns a promise.
all
[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));
});
Blob
Use Blob when available, otherwise BlobBuilder.
constructor
Name | Desc |
---|---|
parts | Blob parts |
options | Options |
const blob = new Blob([]);
BloomFilter
Bloom filter implementation.
Type Definition
class BloomFilter {
constructor(size?: number, k?: number);
add(val: string): void;
test(val: string): boolean;
}
constructor
Name | Desc |
---|---|
size=1024 | Number of buckets |
k=3 | Number of Hash functions |
add
Add an element to the filter.
Name | Desc |
---|---|
val | Value to add |
test
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
Caseless
Modify object props without caring about letter case.
Type Definition
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;
}
constructor
Name | Desc |
---|---|
obj | Target object |
getKey
Get key with preserved casing.
Name | Desc |
---|---|
key | Caseless key |
return | Object key |
set
Set value.
Name | Desc |
---|---|
key | Caseless key |
val | Value to set |
get
Get value.
Name | Desc |
---|---|
key | Caseless key |
return | Value of given key |
remove
Remove value.
Name | Desc |
---|---|
key | Caseless key |
has
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
Class
Create JavaScript class.
Type Definition
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
Color converter.
Type Definition
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;
}
constructor
Name | Desc |
---|---|
color | Color to convert |
toRgb
Get color rgb string format.
toHex
Get color hex string format.
toHsl
Get color hsl string format.
parse
[static] Parse color string into object containing value and model.
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%)'
Delegator
Object delegation.
Type Definition
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;
}
constructor
Name | Desc |
---|---|
host | Host object |
target | Delegation target |
method
Allow method to be accessed on the host object.
Name | Desc |
---|---|
name | Host method name |
target=name | Target method name |
getter
Create a getter.
setter
Create a setter.
access
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
Dispatcher
Flux dispatcher.
Type Definition
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'
});
Emitter
Event emitter class which provides observer pattern.
Type Definition
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;
}
on
Bind event.
off
Unbind event.
once
Bind event that trigger once.
Name | Desc |
---|---|
event | Event name |
listener | Event listener |
emit
Emit event.
Name | Desc |
---|---|
event | Event name |
…args | Arguments passed to listener |
removeAllListeners
Remove all listeners.
Name | Desc |
---|---|
event | Event name |
mixin
[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', 'zso'); // Logs out 'zso'.
Emitter.mixin({});
Enum
Enum type implementation.
Type Definition
class Enum {
size: number;
constructor(map: string[] | { [member: string]: any });
[key: string]: any;
}
constructor
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.
}
FileBlobStore
Binary file storage.
Type Definition
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
Save data to disk.
const store = new FileBlobStore('path/to/file');
store.set('name', Buffer.from('zso'));
process.on('exit', () => store.save());
FileStore
File storage.
Type Definition
class FileStore extends Store {
constructor(path: string, data?: any);
}
constructor
Name | Desc |
---|---|
path | File path to store |
data | Default data |
const store = new FileStore('path/to/file');
store.set('name', 'zso');
HashTable
Hash table implementation.
Type Definition
class HashTable {
constructor(size?: number);
set(key: string, val: any): void;
get(key: string): any;
has(key: string): boolean;
delete(key: string): void;
}
constructor
Name | Desc |
---|---|
size=32 | Bucket size |
set
Set value.
Name | Desc |
---|---|
key | Value key |
val | Value to set |
get
Get value.
Name | Desc |
---|---|
key | Value key |
return | Value of given key |
has
Check if has value.
Name | Desc |
---|---|
key | Value key |
return | True if value exists |
delete
Delete value.
const hashTable = new HashTable(128);
hashTable.set('name', 'ooo9');
hashTable.get('name'); // -> 'ooo9'
hashTable.has('name'); // -> true
hashTable.delete('name');
hashTable.has('name'); // -> false
Heap
Heap implementation.
Type Definition
class Heap {
size: number;
constructor(cmp?: types.AnyFn);
clear(): void;
add(item: any): number;
poll(): any;
peek(): any;
}
size
Heap size.
constructor
Name | Desc |
---|---|
cmp | Comparator |
clear
Clear the heap.
add
Add an item to the heap.
Name | Desc |
---|---|
item | Item to add |
return | Current size |
poll
Retrieve and remove the root item of the heap.
peek
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
HeapSnapshot
V8 heap snapshot manipulator.
Type Definition
class HeapSnapshot {
nodes: LinkedList;
edges: LinkedList;
constructor(profile: any);
}
constructor
Name | Desc |
---|---|
profile | Profile to parse |
nodes
Parsed nodes.
edges
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);
I18n
Simple internationalization library.
Type Definition
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;
}
constructor
Name | Desc |
---|---|
locale | Locale code |
langs | Language data |
set
Add language or append extra keys to existing language.
Name | Desc |
---|---|
locale | Locale code |
lang | Language data |
locale
Set default locale.
Name | Desc |
---|---|
locale | Locale code |
t
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: 'zso' }); // -> 'Hello, zso!'
i18n.locale('cn');
i18n.t('curTime', { time: '5:47 pm' }); // -> '当前时间是 5:47 pm'
JsonTransformer
Json to json transformer.
Type Definition
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;
}
constructor
Name | Desc |
---|---|
data={} | Json object to manipulate |
set
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
Get object value.
Name | Desc |
---|---|
key | Object key |
return | Specified value or whole object |
remove
Remove object value.
Name | Desc |
---|---|
key | Object keys to remove |
map
Shortcut for array map.
Name | Desc |
---|---|
from | From object path |
to | Target object path |
fn | Function invoked per iteration |
filter
Shortcut for array filter.
compute
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: 'ooo9', count: 1}
LinkedList
Doubly-linked list implementation.
Type Definition
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[];
}
size
List size.
head.
First node.
tail
Last node.
push
Add an value to the end of the list.
Name | Desc |
---|---|
val | Value to push |
return | Current size |
pop
Get the last value of the list.
unshift
Add an value to the head of the list.
shift
Get the first value of the list.
rmNode
Remove node.
find
Find node.
Name | Desc |
---|---|
fn | Function invoked per iteration |
return | First value that passes predicate |
forEach
Iterate over the list.
toArr
Convert the list to a JavaScript array.
const linkedList = new LinkedList();
linkedList.push(5);
linkedList.pop(); // -> 5
LocalStore
LocalStorage wrapper.
Type Definition
class LocalStore extends Store {
constructor(name: string, data?: {});
}
Extend from Store.
constructor
Name | Desc |
---|---|
name | LocalStorage item name |
data | Default data |
const store = new LocalStore('zso');
store.set('name', 'zso');
Logger
Simple logger with level filter.
Type Definition
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;
}
constructor
Name | Desc |
---|---|
name | Logger name |
level=DEBUG | Logger level |
setLevel
Set level.
Name | Desc |
---|---|
level | Logger level |
getLevel
Get current level.
trace, debug, info, warn, error
Logging methods.
Log Levels
TRACE, DEBUG, INFO, WARN, ERROR and SILENT.
const logger = new Logger('zso', 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.
});
Lru
Simple LRU cache.
Type Definition
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;
}
constructor
Name | Desc |
---|---|
max | Max items in cache |
has
Check if has cache.
Name | Desc |
---|---|
key | Cache key |
return | True if value exists |
remove
Remove cache.
Name | Desc |
---|---|
key | Cache key |
get
Get cache value.
Name | Desc |
---|---|
key | Cache key |
return | Cache value |
set
Set cache.
Name | Desc |
---|---|
key | Cache key |
val | Cache value |
clear
Clear cache.
const cache = new Lru(50);
cache.set('test', 'zso');
cache.get('test'); // -> 'zso'
MediaQuery
CSS media query listener.
Type Definition
class MediaQuery extends Emitter {
constructor(query: string);
isMatch(): boolean;
}
Extend from Emitter.
constructor
Name | Desc |
---|---|
query | Media query |
isMatch
Return true if given media query matches.
Events
match
Triggered when a media query matches.
unmatch
Opposite of match.
const mediaQuery = new MediaQuery('screen and (max-width:1000px)');
mediaQuery.isMatch(); // -> false
mediaQuery.on('match', () => {
// Do something...
});
MutationObserver
Safe MutationObserver, does nothing if MutationObserver is not supported.
const observer = new MutationObserver(function(mutations) {
// Do something.
});
observer.observe(document.documentElement);
observer.disconnect();
PriorityQueue
Priority queue implementation.
Type Definition
class PriorityQueue {
size: number;
constructor(cmp?: types.AnyFn);
clear(): void;
enqueue(item: any): number;
dequeue(): any;
peek(): any;
}
size
Queue size.
constructor
Name | Desc |
---|---|
cmp | Comparator |
clear
Clear the queue.
enqueue
Add an item to the queue.
Name | Desc |
---|---|
item | Item to add |
return | Current size |
dequeue
Retrieve and remove the highest priority item of the queue.
peek
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' }
Promise
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...
});
PseudoMap
Like es6 Map, without iterators.
Type Definition
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
Queue data structure.
Type Definition
class Queue {
size: number;
clear(): void;
enqueue(item: any): number;
dequeue(): any;
peek(): any;
forEach(iterator: types.AnyFn, context?: any): void;
toArr(): any[];
}
size
Queue size.
clear
Clear the queue.
enqueue
Add an item to the queue.
Name | Desc |
---|---|
item | Item to enqueue |
return | Current size |
dequeue
Remove the first item of the queue.
peek
Get the first item without removing it.
forEach
Iterate over the queue.
Name | Desc |
---|---|
iterator | Function invoked iteration |
ctx | Function context |
toArr
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
QuickLru
LRU implementation without linked list.
Type Definition
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', 'zso');
cache.get('test'); // -> 'zso'
Readiness
Readiness manager.
Type Definition
class Readiness {
signal(tasks: string | string[]): void;
isReady(tasks: string | string[]): boolean;
ready(tasks: string | string[], fn?: types.AnyFn): Promise<void>;
}
signal
Signal task is ready.
Name | Desc |
---|---|
tasks | Ready tasks |
ready
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 |
isReady
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
ReduceStore
Simplified redux like state container.
Type Definition
class ReduceStore {
constructor(reducer: types.AnyFn, initialState: any);
subscribe(listener: types.AnyFn): types.AnyFn;
dispatch(action: any): any;
getState(): any;
}
constructor
Name | Desc |
---|---|
reducer | Function returns next state |
initialState | Initial state |
subscribe
Add a change listener.
Name | Desc |
---|---|
listener | Callback to invoke on every dispatch |
return | Function to unsubscribe |
dispatch
Dispatch an action.
Name | Desc |
---|---|
action | Object representing changes |
return | Same action object |
getState
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
ResizeSensor
Detect if element's size has changed.
Type Definition
class ResizeSensor extends SingleEmitter {
constructor(el: HTMLElement);
destroy(): void;
}
constructor
Name | Desc |
---|---|
element | Element to monitor size |
destroy
Stop monitoring resize event.
const target = document.getElementById('test');
const sensor = new ResizeSensor(target);
sensor.addListener(function() {
// Trigger if element's size changed.
});
Select
Simple wrapper of querySelectorAll to make dom selection easier.
Type Definition
class Select {
constructor(selector: string | Element | Document);
find(selector: string): Select;
each(fn: types.AnyFn): Select;
}
constructor
Name | Desc |
---|---|
selector | Dom selector string |
find
Get desdendants of current matched elements.
Name | Desc |
---|---|
selector | Dom selector string |
each
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
});
Semaphore
Limit simultaneous access to a resource.
Type Definition
class Semaphore {
constructor(counter?: number);
wait(fn: () => void): void;
signal(): void;
}
constructor
Name | Desc |
---|---|
counter=1 | Initial counter |
wait
Wait to execute until counter is bigger than 0.
Name | Desc |
---|---|
fn | Function to execute |
signal
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);
SessionStore
SessionStorage wrapper.
Type Definition
class SessionStore extends Store {
constructor(name: string, data?: any);
}
Extend from Store.
constructor
Name | Desc |
---|---|
name | SessionStorage item name |
data | Default data |
const store = new SessionStore('zso');
store.set('name', 'zso');
SingleEmitter
Event emitter with single event type.
Type Definition
class SingleEmitter {
addListener(listener: types.AnyFn): void;
rmListener(listener: types.AnyFn): void;
emit(...args: any[]): void;
rmAllListeners(): void;
static mixin(obj: any): void;
}
addListener
Add listener.
rmListener
Remove listener.
Name | Desc |
---|---|
listener | Event listener |
rmAllListeners
Remove all listeners.
emit
Call listeners.
Name | Desc |
---|---|
…args | Arguments passed to listener |
mixin
[static] Mixin object class methods.
Name | Desc |
---|---|
obj | Object to mixin |
const event = new SingleEmitter();
event.addListener(function(name) {
console.log(name);
});
event.emit('zso'); // Logs out 'zso'.
Socket
Tiny WebSocket wrapper.
Type Definition
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.
constructor
Name | Desc |
---|---|
url | Url to connect |
options | Connect options |
Available options:
Name | Desc |
---|---|
protocols | Protocol string |
reconnect=true | Try to reconnect if possible |
send
Send message.
Name | Desc |
---|---|
message | Message to send |
close
Close WebSocket.
Name | Desc |
---|---|
code | Status code |
reason | Reason of closing |
connect
Connect WebSocket, called when initialized.
const ws = new Socket('ws://localhost:8001');
ws.on('open', e => ws.send('Hello'));
Stack
Stack data structure.
Type Definition
class Stack {
size: number;
clear(): void;
push(item: any): number;
pop(): any;
peek(): any;
forEach(iterator: types.AnyFn, context?: any): void;
toArr(): any[];
}
size
Stack size.
clear
Clear the stack.
push
Add an item to the stack.
Name | Desc |
---|---|
item | Item to add |
return | Current size |
pop
Get the last item of the stack.
peek
Get the last item without removing it.
forEach
Iterate over the stack.
Name | Desc |
---|---|
iterator | Function invoked iteration |
ctx | Function context |
toArr
Convert the stack to a JavaScript array.
const stack = new Stack();
stack.push(2); // -> 1
stack.push(3); // -> 2
stack.pop(); // -> 3
State
Simple state machine.
Type Definition
class State extends Emitter {
constructor(initial: string, events: any);
is(state: string): boolean;
[event: string]: any;
}
Extend from Emitter.
constructor
Name | Desc |
---|---|
initial | Initial state |
events | Events to change state |
is
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');
Store
Memory storage.
Type Definition
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.
constructor
Name | Desc |
---|---|
data | Initial data |
set
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
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
Remove value.
Name | Desc |
---|---|
key | Key to remove |
clear
Clear all data.
each
Iterate over values.
Name | Desc |
---|---|
fn | Function invoked per iteration |
const store = new Store('test');
store.set('user', { name: 'zso' });
store.get('user').name; // -> 'zso'
store.clear();
store.each(function(val, key) {
// Do something.
});
store.on('change', function(key, newVal, oldVal) {
// It triggers whenever set is called.
});
Trace
Parse, manipulate and generate chrome tracing data.
Type Definition
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() {}
);
Tracing
Easily create chrome tracing data.
Type Definition
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;
}
constructor
Name | Desc |
---|---|
options | Tracing options |
Available options:
Name | Desc |
---|---|
pid | Process id |
tid | Thread id |
processName | Process name |
threadName | Thread name |
start
Start recording.
Name | Desc |
---|---|
cat | Enabled categories |
stop
Stop recording and get result events.
begin
Record begin event.
Name | Desc |
---|---|
cat | Event categories |
name | Event name |
args | Arguments |
end
Record end event.
asyncBegin
Record async begin event.
asyncEnd
Record async end event.
instant
Record instant event.
id
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
Trie data structure.
Type Definition
class Trie {
add(word: string): void;
remove(word: string): void;
has(word: string): boolean;
words(prefix: string): string[];
clear(): void;
}
add
Add a word to trie.
Name | Desc |
---|---|
word | Word to add |
remove
Remove a word from trie.
has
Check if word exists.
words
Get all words with given Prefix.
Name | Desc |
---|---|
prefix | Word prefix |
return | Words with given Prefix |
clear
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
Tween engine for JavaScript animations.
Type Definition
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.
constructor
Name | Desc |
---|---|
obj | Values to tween |
to
Name | Desc |
---|---|
destination | Final properties |
duration | Tween duration |
ease | Easing function |
play
Begin playing forward.
pause
Pause the animation.
paused
Get animation paused state.
progress
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();
Url
Simple url manipulator.
Type Definition
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;
}
constructor
Name | Desc |
---|---|
url=location | Url string |
setQuery
Set query value.
Name | Desc |
---|---|
name | Query name |
val | Query value |
return | this |
Name | Desc |
---|---|
query | query object |
return | this |
rmQuery
Remove query value.
Name | Desc |
---|---|
name | Query name |
return | this |
parse
[static] Parse url into an object.
Name | Desc |
---|---|
url | Url string |
return | Url object |
stringify
[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'
Validator
Object values validation.
Type Definition
class Validator {
constructor(options: types.PlainObj<any>);
validate(object: any): string | boolean;
static plugins: any;
static addPlugin(name: string, plugin: types.AnyFn): void;
}
constructor
Name | Desc |
---|---|
options | Validation configuration |
validate
Validate object.
Name | Desc |
---|---|
obj | Object to validate |
return | Validation result, true means ok |
addPlugin
[static] Add plugin.
Name | Desc |
---|---|
name | Plugin name |
plugin | Validation handler |
Default Plugins
Required, number, boolean, string and regexp.
Validator.addPlugin('custom', function(val, key, config) {
if (typeof val === 'string' && val.length === 5) return true;
return key + ' should be a string with length 5';
});
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: 'zso' }); // -> true
Wrr
Weighted Round Robin implementation.
Type Definition
class Wrr {
size: number;
set(val: any, weight: number): void;
get(val: any): number | void;
remove(val: any): void;
clear(): void;
next(): any;
}
size
Pool size.
set
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
Get weight of given value.
Name | Desc |
---|---|
val | Value to get |
return | Weight of the value |
remove
Remove given value.
Name | Desc |
---|---|
val | Value to remove |
next
Get next value from pool.
clear
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
abbrev
Calculate the set of unique abbreviations for a given set of strings.
Type Definition
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'}
after
Create a function that invokes once it's called n or more times.
Type Definition
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 |
```javascript const fn = after(5, function() { //
你可能也喜欢
- 3pm-module-timesheet 中文文档教程
- @0655-dev/webpack-package-template 中文文档教程
- @0x0/restify 中文文档教程
- @0x4d/locationar 中文文档教程
- @2060digital/prettier-config 中文文档教程
- @3test/wanchain-order-gateway 中文文档教程
- @4geit/rct-cell-component 中文文档教程
- @4geit/rct-notification-menu-component 中文文档教程
- @a-a-game-studio/aa-front 中文文档教程
- @aads/lambda-logger 中文文档教程