basic-collection
A generic collection class to contain array-like data.
Installation
$ npm install basic-collection
To port it to Browser or any other environment (not node), use a JS bundler (Browserify, Webpack, etc.).
Basic usage
import BasicCollection from "basic-collection";
let Collection = new BasicCollection;
Collection.set( "key_1", "value_1" );
Collection.set( "key_2", "value_2" );
Collection.set( 1234567, true );
Collection.get( "key_1" );
Collection.get( "key_2" );
Collection.get( "key_3", "default" );
Collection.has( "key_1" );
Collection.has( "key_2" );
Collection.has( "key_3" );
Collection.remove( "key_2" );
console.log( Collection.size );
console.log( Collection.keys );
console.log( Collection.values );
console.log( Collection.entries );
Collection.each( ( key, value, map ) => {
console.log( `Collection[${key}] = ${value}` );
} );
Collection.clear();
console.log( Collection.size );
Creating custom collections
import BasicCollection from "basic-collection";
class MyCollection {
constructor( parameters ) {
super( parameters );
}
normalize( key ) {
return `transformed_${key}`;
}
}
let Collection = new MyCollection;
Collection.set( "key_1", "value_1" );
Collection.set( "key_2", "value_2" );
console.log( Collection.keys );
API
Method | Description | Access | Return |
---|
normalize( key ) | Normalizes data key. | protected | string |
set( key, value ) | Sets an attribute for the current collection. If the attribute name already exists, its value will be overwritten. | public | null |
get( key[, default] ) | Returns an attribute of the collection or a default value if the key does not exist. | public | mixed |
has( key ) | Checks if an attribute exists in the current collection. | public | bool |
remove( key ) | Removes an attribute from the current collection. | public | null |
clear() | Clears all values. | public | null |
each( callback ) | Executes a callback for each element of this Collection. | public | null |
size | Counts parameters. | public | int |
entries | Returns a new Iterator object that contains an array of [key, value] for each element in the Collection in insertion order. | public | iterable |
keys | Returns a new Iterator object that contains the keys for each element in the Collection in insertion order. | public | iterable |
values | Returns a new Iterator object that contains the values for each element in the Collection in insertion order. | public | iterable |
Tests
$ npm test