Js Collection is an object collection class used to simplify using array of objects. This pattern or methodology rather, is commonly used in oo designs. Together with iterator functionality it simplifies traversal and manipulation of objects during the iteration and adds commonality to your arrays.
Example
myCollection = new JsCollection(myArrayOfObjects);
while(myCollection.hasNext()) {
element = testCollection.next();
element.functionCall();
}
myCollection.orderBy('name');
myArrayOfObjects = myCollection.getAll();
####Add elements to your collection #####Within a loop Adds a single object at the end of the array collection
myCollection.add(myObject);
#####Complete array You can set an array of objects directly
myCollection.setArray(myArrayOfObjects);
####Iteration You can iterate the collection in multiple ways:
each
myCollection.each(function(key, element) {}):
while
while(myCollection.hasNext()) {
element = testCollection.next();
}
for
for(var i = 0; i < testCollection.count(); i++) {
element = testCollection.getByKey(i);
}
Iterator functions
Function | Description |
---|---|
count() |
Returns number of objects in the collection |
position() |
Returns the current iterator position |
first() |
Returns the first element in the collection |
last() |
Returns the last element in the collection |
current() |
Returns current element according to the iterator position |
next() |
Returns current element then increases the iterator position by one |
hasNext() |
Returns true or false if the collection has more elements |
rewind() |
Resets the iterator position and returns the first element in the collection |
####Ordering
myCollection.orderBy('name', 'desc');
add(element)
: Add an element to the collectionget(key|null)
: If key is defined get element by key, else get current elementgetAll()
: Get all elements currently in the collectioncount()
: Returns number of elements in the collectiongetKeys()
: Returns an array of the collection keyscontainsKey(key)
: Check if a key exists or notremove(key|null)
: If key is defined remove element by key, else remove current elementreplace(key, element)
: Replace object with keyfirst()
: Get the first element in the collectionlast()
: Get the last element in the collectionposition()
: Returns current iterator positionnext()
: Returns current object and increases the iteratorhasNext()
: Returns true or false if the collection has more elementscurrent()
: Returns current elementrewind()
: Resets the iteratorclear()
: Clear the collection, remove all elementssetArray()
: Fill the collection with a arrayeach(callback(key, value))
: Iterate through all elementsorderBy(property, direction)
: Order elements by element property and direction