npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

zso

v0.5.8

Published

Useful utility collection with zero dependencies

Downloads

492

Readme

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.

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

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.

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.

$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.

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

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

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.

| Name | Desc | | ------- | ------------------ | | element | Elements to delete |

$remove('#test');

$safeEls

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

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

| Name | Desc | | ------- | ---------------- | | element | Elements to show |

$show('#test');

Benchmark

JavaScript Benchmark.

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.

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.

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.

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

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.

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.

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.

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

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.

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

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

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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

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.

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

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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

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

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.

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.

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.

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.

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.

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

| Name | Desc | | ------ | ------------------------------ | | n | Number of calls before invoked | | fn | Function to restrict | | return | New restricted function |

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