0.5.8 • Published 1 year ago

zso v0.5.8

Weekly downloads
-
License
MIT
Repository
github
Last release
1 year ago

Zso

NPM version Test coverage Size License

\$

jQuery like style dom manipulator.

Available methods

offset, hide, show, first, last, get, eq, on, off, html, text, val, css, attr, data, rmAttr, remove, addClass, rmClass, toggleClass, hasClass, append, prepend, before, after

const $btn = $('#btn');
$btn.html('eustia');
$btn.addClass('btn');
$btn.show();
$btn.on('click', function() {
    // Do something...
});

\$attr

Element attribute manipulation.

Get the value of an attribute for the first element in the set of matched elements.

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.

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.

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.

$data('#test', 'attr1', 'eustia');

\$event

bind events to certain dom elements.

function clickHandler() {
    // Do something...
}
$event.on('#test', 'click', clickHandler);
$event.off('#test', 'click', clickHandler);

\$insert

Insert html on different position.

before

Insert content before elements.

after

Insert content after elements.

prepend

Insert content to the beginning of elements.

append

Insert content to the end of elements.

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.

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.

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.

NameDesc
elementElements to delete
$remove('#test');

\$safeEls

Convert value into an array, if it's a string, do querySelector.

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.

NameDesc
elementElements to show
$show('#test');

Benchmark

JavaScript Benchmark.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

constructor

NameDesc
pathFile path to store
dataDefault data
const store = new FileStore('path/to/file');
store.set('name', 'zso');

HashTable

Hash table implementation.

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.

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.

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.

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.

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.

size

List size.

head.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

NameDesc
nNumber of calls before invoked
fnFunction to restrict
returnNew restricted function
const fn = after(5, function() {
    // 
0.5.8

1 year ago

0.5.7

1 year ago

0.5.6

1 year ago

0.5.4

1 year ago

0.5.3

1 year ago

0.5.2

1 year ago

0.5.1

1 year ago

0.5.0

1 year ago

0.4.3

1 year ago

0.4.2

1 year ago

0.4.1

1 year ago

0.4.0

1 year ago

0.3.1

1 year ago

0.3.0

1 year ago

0.2.0

1 year ago

0.1.0

1 year ago

0.0.3

1 year ago

0.0.2

1 year ago

0.0.1

1 year ago