zso 中文文档教程

发布于 2年前 浏览 14 项目主页 更新于 2年前

Zso

NPM versionTest coverageSizeLicense

\$

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.

NameDesc
elementElements to manipulate
nameAttribute name
returnAttribute value of first element

Set one or more attributes for the set of matched elements.

NameDesc
elementElements to manipulate
nameAttribute name
valAttribute value
NameDesc
elementElements to manipulate
attributesObject of attribute-value pairs to set

remove

Remove an attribute from each element in the set of matched elements.

NameDesc
elementElements to manipulate
nameAttribute 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.

NameDesc
elementElements to manipulate
namesClasses to add

has

Determine whether any of the matched elements are assigned the given class.

NameDesc
elementElements to manipulate
nameClass name
returnTrue 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.

NameDesc
elementElements to manipulate
nameClass name to toggle

remove

Remove a single class, multiple classes, or all classes from each element in the set of matched elements.

NameDesc
elementElements to manipulate
nameClass 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.

NameDesc
elementElements to manipulate
nameProperty name
returnCss value of first element

Set one or more CSS properties for the set of matched elements.

NameDesc
elementElements to manipulate
nameProperty name
valCss value
NameDesc
elementElements to manipulate
propertiesObject 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.

NameDesc
elementElements to manipulate
contentHtml 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;

NameDesc
elementElements to get offset
returnElement 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);

NameDesc
elementElements 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[];

NameDesc
valValue to convert
returnArray 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;

NameDesc
elementElements 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

NameDesc
fnCode for speed testing
optionsBenchmark options

Available options:

NameDesc
minTime=50Time needed to reduce uncertainty
maxTime=5000Maximum time for running benchmark
minSamples=5Minimum sample size
delay=5Delay between test cycles
nameBenchmark 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

NameDesc
partsBlob parts
optionsOptions
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

NameDesc
size=1024Number of buckets
k=3Number of Hash functions

add

Add an element to the filter.

NameDesc
valValue to add

test

Test if an element is in the filter.

NameDesc
valValue to test
returnTrue 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

NameDesc
objTarget object

getKey

Get key with preserved casing.

NameDesc
keyCaseless key
returnObject key

set

Set value.

NameDesc
keyCaseless key
valValue to set

get

Get value.

NameDesc
keyCaseless key
returnValue of given key

remove

Remove value.

NameDesc
keyCaseless key

has

Determine whether target object has given key.

NameDesc
keyCaseless key
returnTrue 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;

NameDesc
methodsPublic methods
[staticsStatic methods
returnFunction 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

NameDesc
colorColor 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.

NameDesc
colorColor string
returnObject 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

NameDesc
hostHost object
targetDelegation target

method

Allow method to be accessed on the host object.

NameDesc
nameHost method name
target=nameTarget 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;
}

Related docs

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.

NameDesc
eventEvent name
listenerEvent listener

emit

Emit event.

NameDesc
eventEvent name
…argsArguments passed to listener

removeAllListeners

Remove all listeners.

NameDesc
eventEvent name

mixin

[static] Mixin object class methods.

NameDesc
objObject 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

NameDesc
arrArray of strings
NameDesc
objPairs 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

NameDesc
pathFile path to store
dataDefault 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

NameDesc
size=32Bucket size

set

Set value.

NameDesc
keyValue key
valValue to set

get

Get value.

NameDesc
keyValue key
returnValue of given key

has

Check if has value.

NameDesc
keyValue key
returnTrue 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

NameDesc
cmpComparator

clear

Clear the heap.

add

Add an item to the heap.

NameDesc
itemItem to add
returnCurrent 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

NameDesc
profileProfile 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

NameDesc
localeLocale code
langsLanguage data

set

Add language or append extra keys to existing language.

NameDesc
localeLocale code
langLanguage data

locale

Set default locale.

NameDesc
localeLocale code

t

Get translation text.

NameDesc
pathPath of translation to get
dataData to pass in
returnTranslation 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

NameDesc
data={}Json object to manipulate

set

Set object value.

NameDesc
keyObject key
valValue to set

If key is not given, the whole source object is replaced by val.

get

Get object value.

NameDesc
keyObject key
returnSpecified value or whole object

remove

Remove object value.

NameDesc
keyObject keys to remove

map

Shortcut for array map.

NameDesc
fromFrom object path
toTarget object path
fnFunction invoked per iteration

filter

Shortcut for array filter.

compute

Compute value from several object values.

NameDesc
fromSource values
toTarget object path
fnFunction 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.

First node.

tail

Last node.

push

Add an value to the end of the list.

NameDesc
valValue to push
returnCurrent 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.

NameDesc
fnFunction invoked per iteration
returnFirst 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

NameDesc
nameLocalStorage item name
dataDefault 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

NameDesc
nameLogger name
level=DEBUGLogger level

setLevel

Set level.

NameDesc
levelLogger 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

NameDesc
maxMax items in cache

has

Check if has cache.

NameDesc
keyCache key
returnTrue if value exists

remove

Remove cache.

NameDesc
keyCache key

get

Get cache value.

NameDesc
keyCache key
returnCache value

set

Set cache.

NameDesc
keyCache key
valCache 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

NameDesc
queryMedia 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

NameDesc
cmpComparator

clear

Clear the queue.

enqueue

Add an item to the queue.

NameDesc
itemItem to add
returnCurrent 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.

Promises spec

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.

NameDesc
itemItem to enqueue
returnCurrent size

dequeue

Remove the first item of the queue.

peek

Get the first item without removing it.

forEach

Iterate over the queue.

NameDesc
iteratorFunction invoked iteration
ctxFunction 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.

NameDesc
tasksReady tasks

ready

Register ready callback.

NameDesc
tasksTasks to listen
fnCallback to trigger if tasks are ready
returnPromise that will be resolved when ready

isReady

Check if tasks are ready.

NameDesc
tasksTasks to check
returnTrue 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

NameDesc
reducerFunction returns next state
initialStateInitial state

subscribe

Add a change listener.

NameDesc
listenerCallback to invoke on every dispatch
returnFunction to unsubscribe

dispatch

Dispatch an action.

NameDesc
actionObject representing changes
returnSame 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

NameDesc
elementElement 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

NameDesc
selectorDom selector string

find

Get desdendants of current matched elements.

NameDesc
selectorDom selector string

each

Iterate over matched elements.

NameDesc
fnFunction 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

NameDesc
counter=1Initial counter

wait

Wait to execute until counter is bigger than 0.

NameDesc
fnFunction 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

NameDesc
nameSessionStorage item name
dataDefault 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.

NameDesc
listenerEvent listener

rmAllListeners

Remove all listeners.

emit

Call listeners.

NameDesc
…argsArguments passed to listener

mixin

[static] Mixin object class methods.

NameDesc
objObject 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

NameDesc
urlUrl to connect
optionsConnect options

Available options:

NameDesc
protocolsProtocol string
reconnect=trueTry to reconnect if possible

send

Send message.

NameDesc
messageMessage to send

close

Close WebSocket.

NameDesc
codeStatus code
reasonReason 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.

NameDesc
itemItem to add
returnCurrent size

pop

Get the last item of the stack.

peek

Get the last item without removing it.

forEach

Iterate over the stack.

NameDesc
iteratorFunction invoked iteration
ctxFunction 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

NameDesc
initialInitial state
eventsEvents to change state

is

Check current state.

NameDesc
stateState to check
returnTrue 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

NameDesc
dataInitial data

set

Set value.

NameDesc
keyValue key
valValue to set

Set values.

NameDesc
valuesKey value pairs

This emit a change event whenever is called.

get

Get value.

NameDesc
keyValue key
returnValue of given key

Get values.

NameDesc
keysArray of keys
returnKey value pairs

remove

Remove value.

NameDesc
keyKey to remove

clear

Clear all data.

each

Iterate over values.

NameDesc
fnFunction 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

NameDesc
optionsTracing options

Available options:

NameDesc
pidProcess id
tidThread id
processNameProcess name
threadNameThread name

start

Start recording.

NameDesc
catEnabled categories

stop

Stop recording and get result events.

begin

Record begin event.

NameDesc
catEvent categories
nameEvent name
argsArguments

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.

NameDesc
wordWord to add

remove

Remove a word from trie.

has

Check if word exists.

words

Get all words with given Prefix.

NameDesc
prefixWord prefix
returnWords 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

NameDesc
objValues to tween

to

NameDesc
destinationFinal properties
durationTween duration
easeEasing function

play

Begin playing forward.

pause

Pause the animation.

paused

Get animation paused state.

progress

Update or get animation progress.

NameDesc
progressNumber 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

NameDesc
url=locationUrl string

setQuery

Set query value.

NameDesc
nameQuery name
valQuery value
returnthis
NameDesc
queryquery object
returnthis

rmQuery

Remove query value.

NameDesc
nameQuery name
returnthis

parse

[static] Parse url into an object.

NameDesc
urlUrl string
returnUrl object

stringify

[static] Stringify url object into a string.

NameDesc
urlUrl object
returnUrl string

An url object contains the following properties:

NameDesc
protocolThe protocol scheme of the URL (e.g. http:)
slashesA boolean which indicates whether the protocol is followed by two forward slashes (//)
authAuthentication information portion (e.g. username:password)
hostnameHost name without port number
portOptional port number
pathnameURL path
queryParsed object containing query string
hashThe "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

NameDesc
optionsValidation configuration

validate

Validate object.

NameDesc
objObject to validate
returnValidation result, true means ok

addPlugin

[static] Add plugin.

NameDesc
namePlugin name
pluginValidation 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.

NameDesc
valValue to set
weightWeight of the value

get

Get weight of given value.

NameDesc
valValue to get
returnWeight of the value

remove

Remove given value.

NameDesc
valValue 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>;

NameDesc
namesList of names
returnAbbreviation 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;

NameDesc
nNumber of calls before invoked
fnFunction to restrict
returnNew restricted function

```javascript const fn = after(5, function() { //

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文