Home Reference Source Repository
import Collection from 'collectionsjs/src/collection.js'
public class | source

Collection

The Collection object.

Example:

let collection = new Collection([1, 2, 3]);

Static Method Summary

Static Public Methods
public static

collect(collectable: Array): Collection

Static constructor.

public static

macro(name: string, callback: function): *

Registers a new method on the collection prototype for future use.

Constructor Summary

Public Constructor
public

The collection constructor.

Member Summary

Public Members
public

The internal array.

Method Summary

Public Methods
public

add(item: *): Collection

Adds an item to the collection.

public

all(): Array

Gets the collected elements in an array.

public

average(property: function | string): number

Gets the average value of the array or a property or a callback return value.

public

Chunks the collection into a new collection with equal length arrays as its items.

public

concat(collection: Array | Collection): Collection

Concatnates the collection with an array or another collection.

public

Checks if there is at least one occurance of an element using a closure.

public

Gets the number of items in the collection.

public

each(callback: function): Collection

Executes a callback for each element in the collection.

public

filter(callback: function): Collection

Filters the collection using a predicate (callback that returns a boolean).

public

find(item: *): number

Returns the index of an element.

public

first(callback: function): *

Gets the first element satisfying a critera.

public

Flattens the collection elements.

public

get(index: number): *

Gets an element at a specified index.

public

has(item: *): boolean

Checks if a collection has a specific item.

public

join(seperator: string): string

Joins the collection elements into a string.

public

Gets the collection elements keys in a new collection.

public

last(callback: function): *

Gets the last element to satisfy a callback.

public

map(callback: function): Collection

Maps each element using a mapping function and collects the mapped items.

public

pluck(property: string): Collection

Extracts a property from the objects in the collection.

public

push(item: *): Collection

Adds an element to the collection.

public

reduce(callback: function, initial: *): *

Reduces the collection to a single value using a reducing function.

public

reject(callback: function): Collection

Removes the elements that do not satisfy the predicate.

public

remove(item: *): boolean

Removes an item from the collection.

public

Reverses the collection order.

public

Skips a specified number of elements.

public

slice(start: number, end: number): Collection

Slices the collection starting from a specific index and ending at a specified index.

public

sort(compare: function): Collection

Sorts the elements of a collection and returns a new sorted collection.

public

sortBy(property: string, order: string): Collection

Sorts the collection by key value comaprison, given that the items are objects.

public

{stringifies the collection using JSON.stringify API.

public

sum(property: undefined | string | function): *

Sums the values of the array, or the properties, or the result of the callback.

public

Gets a new collection with the number of specified items from the begining or the end.

public

Remove duplicate values from the collection.

public

Gets the values without preserving the keys.

public

where(callback: function | string, value: *): Collection

Filters the collection using a callback or equality comparison to a property in each item.

public

Pairs each item in the collection with another array item in the same index.

Static Public Methods

public static collect(collectable: Array): Collection source

Static constructor. cool if you don't like using the 'new' keyword.

Params:

NameTypeAttributeDescription
collectable Array

the array or the string to wrapped in a collection.

Return:

Collection

A collection that wraps the collectable items.

Example:

const collection = Collection.collect([1, 2, 3]);
console.log(collection.all()); // [1, 2, 3]

public static macro(name: string, callback: function): * source

Registers a new method on the collection prototype for future use. The closure gets the collection object passed as the first parameter then other parameters gets passed after.

Params:

NameTypeAttributeDescription
name string

The name of the macro function.

callback function

A closure containing the behavior of the macro.

Return:

*

returns your callback result.

Example:

Collection.macro('addToMembers', (collection, n) => collection.map(item => item + n));
const col2 = new Collection([1, 2, 3, 4]).addToMembers(3);
console.log(col2.all()); // [4, 5, 6, 7]

Public Constructors

public constructor(items: Array): Collection source

The collection constructor.

Params:

NameTypeAttributeDescription
items Array
  • optional
  • default: []

the array to collect.

Return:

Collection

A Collection object.

Public Members

public items: Array | Object source

The internal array.

Public Methods

public add(item: *): Collection source

Adds an item to the collection.

Params:

NameTypeAttributeDescription
item *

the item to be added.

Return:

Collection

the collection object.

Example:

const collection = new Collection();
collection.add('Arya');
console.log(collection.first()); //outputs 'Arya'

public all(): Array source

Gets the collected elements in an array.

Return:

Array

the internal array.

Example:

const collection = new Collection([1, 2, 3]);
console.log(collection.all()); // [1, 2, 3]

public average(property: function | string): number source

Gets the average value of the array or a property or a callback return value. If no property is provided: it will calculate the average value of the array (Numeric array). If property is a string: it will calculate the average value of that property for all objects in the array. If Property is a callback: the the averaging will use the value returned instead.

Params:

NameTypeAttributeDescription
property function | string
  • optional
  • default: null

The property name or the callback function. defaults to null.

Return:

number

The average value.

Example:

Averaging elements
const collection = new Collection([1, 2, 3]);
console.log(collection.average()); // 2
Averaging a property
const collection = new Collection([
    { name: 'Arya Stark', age: 9 },
    { name: 'Bran Stark', age: 7 },
    { name: 'Jon Snow', age: 14 }
]);
console.log(collection.average('age')); // 10
Averaging using a callback
const collection = new Collection([
    { name: 'Arya Stark', age: 9 },
    { name: 'Bran Stark', age: 7 },
    { name: 'Jon Snow', age: 14 }
]);
console.log(collection.average(i => i.age)); // 10

public chunk(size: number): Collection source

Chunks the collection into a new collection with equal length arrays as its items.

Params:

NameTypeAttributeDescription
size number

the size of each chunk.

Return:

Collection

the new collection.

Example:

const collection = new Collection([1, 2, 3, 4, 5]).chunk(2);
console.log(collection.all()); // [[1, 2], [3, 4], [5]]

public concat(collection: Array | Collection): Collection source

Concatnates the collection with an array or another collection.

Params:

NameTypeAttributeDescription
collection Array | Collection

the array or the collection to be concatenated with.

Return:

Collection

concatenated collection.

Example:

const collection = new Collection([1, 2, 3]);
const array = [4, 5, 6]; // or another collection.
const newCollection = collection.concat(array);
console.log(newCollection.all()); // [1, 2, 3, 4, 5, 6]

public contains(closure: function): boolean source

Checks if there is at least one occurance of an element using a closure.

Params:

NameTypeAttributeDescription
closure function

The closure the be used on each element.

Return:

boolean

true if at least one occurance exist, false otherwise.

Example:

const collection = new Collection([
    { name: 'John Snow', age: 14 },
    { name: 'Bran Stark', age: 7 },
    { name: 'Arya Stark', age: 9 }
]);

collection.contains(stark => stark.name === 'John Snow'); // true
collection.contains(stark => stark.name === 'Eddard Stark'); // false

public count(): number source

Gets the number of items in the collection.

Return:

number

Number of items in the collection.

Example:

const collection = new Collection([1, 2, 3]);
console.log(collection.count()); // 3

public each(callback: function): Collection source

Executes a callback for each element in the collection.

Params:

NameTypeAttributeDescription
callback function

the callback to be excuted for each item.

Return:

Collection

The collection object.

Example:

const collection = new Collection(['this', 'is', 'collectionjs']);
collection.each(t => console.log(t)); // this is collectionjs

public filter(callback: function): Collection source

Filters the collection using a predicate (callback that returns a boolean).

Params:

NameTypeAttributeDescription
callback function

A function that returns a boolean expression.

Return:

Collection

Filtered collection.

Example:

const collection = new Collection([
    { name: 'Arya Stark', age: 9 },
    { name: 'Bran Stark', age: 7 },
    { name: 'Jon Snow', age: 14 }
]).filter(stark => stark.age === 14);
console.log(collection.all()); // [{ name: 'Jon Snow', age: 14 }]

public find(item: *): number source

Returns the index of an element.

Params:

NameTypeAttributeDescription
item *

The item to be searched.

Return:

number

The index of the item. -1 means it wasn't found.

Example:

const collection = new Collection(['jon', 'arya', 'bran']);
console.log(collection.find('bran')); // 2
console.log(collection.find('ed')); // -1

public first(callback: function): * source

Gets the first element satisfying a critera.

Params:

NameTypeAttributeDescription
callback function
  • optional
  • default: null

the predicate (callback) that will be applied on items.

Return:

*

the first item to satisfy the critera.

Example:

Using a callback
const first = new Collection([
    { name: 'Bran Stark', age: 7 },
    { name: 'Arya Stark', age: 9 },
    { name: 'Jon Snow', age: 14 }
]).first(item => item.age > 7);

console.log(first); // { name: 'Arya Stark', age: 9 }
No Arguments
const first = new Collection([
    { name: 'Bran Stark', age: 7 },
    { name: 'Arya Stark', age: 9 },
    { name: 'Jon Snow', age: 14 }
]).first();

console.log(first); // { name: 'Bran Stark', age: 7 }

public flatten(deep: Boolean): Collection source

Flattens the collection elements.

Params:

NameTypeAttributeDescription
deep Boolean
  • optional
  • default: false

recursively flatten the items (multi-level).

Return:

Collection

the flattened collection.

Example:

Just one level
const collection = new Collection([1, [2, [3, [4]], 5]]).flatten();
console.log(collection.all()); // [1, 2, [3, [4]], 5]
Deep
const collection = new Collection([1, [2, [3, [4]], 5]]).flatten(true);
console.log(collection.all()); // [1, 2, 3, 4, 5]

public get(index: number): * source

Gets an element at a specified index.

Params:

NameTypeAttributeDescription
index number

the index of the item.

Return:

*

the item at that index.

Example:

const collection = new Collection([1, 2, 3]);
console.log(collection.get(2)); // 3

public has(item: *): boolean source

Checks if a collection has a specific item.

Params:

NameTypeAttributeDescription
item *

The item to be searched.

Return:

boolean

true if exists, false otherwise.

Example:

const collection = new Collection([1, 2, 3, 4]);

console.log(collection.has(2)); // true
console.log(collection.has(5)); // false

public join(seperator: string): string source

Joins the collection elements into a string.

Params:

NameTypeAttributeDescription
seperator string
  • optional
  • default: ','

The seperator between each element and the next.

Return:

string

The joined string.

Example:

const collection = new Collection(['Wind', 'Rain', 'Fire']);
console.log(collection.join()); // 'Wind,Rain,Fire'
console.log(collection.join(', ')); 'Wind, Rain, Fire'

public keys(): Collection source

Gets the collection elements keys in a new collection.

Return:

Collection

The keys collection.

Example:

Objects
const keys = new Collection({
    arya: 10,
    john: 20,
    potato: 30
}).keys();
console.log(keys); // ['arya', 'john', 'potato']
Regular Array
const keys = new Collection(['arya', 'john', 'potato']).keys();
console.log(keys); // ['0', '1', '2']

public last(callback: function): * source

Gets the last element to satisfy a callback.

Params:

NameTypeAttributeDescription
callback function
  • optional
  • default: null

the predicate to be checked on all elements.

Return:

*

The last element in the collection that satisfies the predicate.

Example:

Using a callback
const last = new Collection([
    { name: 'Bran Stark', age: 7 },
    { name: 'Arya Stark', age: 9 },
    { name: 'Jon Snow', age: 14 }
]).last(item => item.age > 7);

console.log(last); // { name: 'Jon Snow', age: 14 }
No Arguments
const last = new Collection([
    { name: 'Bran Stark', age: 7 },
    { name: 'Arya Stark', age: 9 },
    { name: 'Jon Snow', age: 14 }
]).last();

console.log(last); // { name: 'Jon Snow', age: 14 }

public map(callback: function): Collection source

Maps each element using a mapping function and collects the mapped items.

Params:

NameTypeAttributeDescription
callback function

the mapping function.

Return:

Collection

collection containing the mapped items.

Example:

const collection = new Collection([
    { name: 'Bran Stark', age: 7 },
    { name: 'Arya Stark', age: 9 },
    { name: 'Jon Snow', age: 14 }
]).map(stark => stark.name);
console.log(collection.all()); ['Bran Stark', 'Arya Stark', 'Jon Snow']

public pluck(property: string): Collection source

Extracts a property from the objects in the collection.

Params:

NameTypeAttributeDescription
property string

the name of the property to be extracted.

Return:

Collection

A collection with the extracted items.

Example:

const collection = new Collection([
    { name: 'Bran Stark', age: 7 },
    { name: 'Arya Stark', age: 9 },
    { name: 'Jon Snow', age: 14 }
]).pluck('name');
console.log(collection.all()); ['Bran Stark', 'Arya Stark', 'Jon Snow']

public push(item: *): Collection source

Adds an element to the collection.

Params:

NameTypeAttributeDescription
item *

the item to be added.

Return:

Collection

The collection object.

Example:

const collection = new Collection().push('First');
console.log(collection.first()); // "First"

public reduce(callback: function, initial: *): * source

Reduces the collection to a single value using a reducing function.

Params:

NameTypeAttributeDescription
callback function

the reducing function.

initial *

initial value.

Return:

*

The reduced results.

Example:

const value = new Collection([1, 2, 3]).reduce(
    (previous, current) => previous + current,
     0
 );
 console.log(value); // 6

public reject(callback: function): Collection source

Removes the elements that do not satisfy the predicate.

Params:

NameTypeAttributeDescription
callback function

the predicate used on each item.

Return:

Collection

A collection without the rejected elements.

Example:

const collection = new Collection([
    { name: 'Arya Stark', age: 9 },
    { name: 'Bran Stark', age: 7 },
    { name: 'Jon Snow', age: 14 }
]).reject(stark => stark.age < 14);
console.log(collection.all()); // [{ name: 'Jon Snow', age: 14 }]

public remove(item: *): boolean source

Removes an item from the collection.

Params:

NameTypeAttributeDescription
item *

the item to be searched and removed, first occurance will be removed.

Return:

boolean

True if the element was removed, false otherwise.

Example:

const collection = new Collection(['john', 'arya', 'bran']);
collection.remove('john');
console.log(collection.all()); // ['arya', 'bran']

public reverse(): Collection source

Reverses the collection order.

Return:

Collection

A new collection with the reversed order.

Example:

const collection = new Collection(['one', 'two', 'three']).reverse();
console.log(collection.all()); // ['three', 'two', 'one']

public skip(count: number): Collection source

Skips a specified number of elements.

Params:

NameTypeAttributeDescription
count number

the number of items to be skipped.

Return:

Collection

A collection without the skipped items.

Example:

const collection = new Collection(['John', 'Arya', 'Bran', 'Sansa']).skip(2);
console.log(collection.all()); // ['Bran', 'Sansa']

public slice(start: number, end: number): Collection source

Slices the collection starting from a specific index and ending at a specified index.

Params:

NameTypeAttributeDescription
start number

The zero-based starting index.

end number
  • optional
  • default: length

The zero-based ending index.

Return:

Collection

A collection with the sliced items.

Example:

start and end are specified
const collection = new Collection([0, 1, 2, 3, 4, 5, 6]).slice(2, 4);
console.log(collection.all()); // [2, 3]
only start is specified
const collection = new Collection([0, 1, 2, 3, 4, 5, 6]).slice(2);
console.log(collection.all()); // [2, 3, 4, 5, 6]

public sort(compare: function): Collection source

Sorts the elements of a collection and returns a new sorted collection. note that it doesn't change the orignal collection and it creates a shallow copy.

Params:

NameTypeAttributeDescription
compare function
  • optional
  • default: undefined

the compare function.

Return:

Collection

A new collection with the sorted items.

Example:

const collection = new Collection([5, 3, 4, 1, 2]);
const sorted = collection.sort();
// original collection is intact.
console.log(collection.all()); // [5, 3, 4, 1, 2]
console.log(sorted.all()); // [1, 2, 3, 4, 5]

public sortBy(property: string, order: string): Collection source

Sorts the collection by key value comaprison, given that the items are objects. It creates a shallow copy and retains the order of the orignal collection.

Params:

NameTypeAttributeDescription
property string

the key or the property to be compared.

order string
  • optional
  • default: 'asc'

The sorting order. use 'asc' for ascending or 'desc' for descending, case insensitive.

Return:

Collection

A new Collection with the sorted items.

Example:

const collection = new Collection([
    { name: 'Jon Snow', age: 14 },
    { name: 'Arya Stark', age: 9 },
    { name: 'Bran Stark', age: 7 },
]).sortBy('age');

console.log(collection.pluck('name').all()); // ['Brand Stark', 'Arya Stark', 'Jon Snow']

public stringify(): string source

{stringifies the collection using JSON.stringify API.

Return:

string

The stringified value.

Example:

const collection = new Collection([1, 2, 3]);
console.log(collection.stringify()); // "[1,2,3]"

public sum(property: undefined | string | function): * source

Sums the values of the array, or the properties, or the result of the callback.

Params:

NameTypeAttributeDescription
property undefined | string | function
  • optional
  • default: null

the property to be summed.

Return:

*

The sum of values used in the summation.

Example:

Summing elements
const collection = new Collection([1, 2, 3]);
console.log(collection.sum()); // 6
Summing a property
const collection = new Collection([
    { name: 'Arya Stark', age: 9 },
    { name: 'Bran Stark', age: 7 },
    { name: 'Jon Snow', age: 14 }
]);
console.log(collection.sum('age')); // 30
Summing using a callback
const collection = new Collection([
    { name: 'Arya Stark', age: 9 },
    { name: 'Bran Stark', age: 7 },
    { name: 'Jon Snow', age: 14 }
]);
console.log(collection.sum(i => i.age + 1)); // 33

public take(count: number): Collection source

Gets a new collection with the number of specified items from the begining or the end.

Params:

NameTypeAttributeDescription
count number

the number of items to take. Takes from end if negative.

Return:

Collection

A collection with the taken items.

Example:

From the beginning
const collection = new Collection([1, 2, 3, 4, 5]).take(3);
console.log(collection.all()); // [1, 2, 3]
From the end
const collection = new Collection([1, 2, 3, 4, 5]).take(-3);
console.log(collection.all()); // [5, 4 ,3]

public unique(callback: function | string): Collection source

Remove duplicate values from the collection.

Params:

NameTypeAttributeDescription
callback function | string
  • optional
  • default: null

The predicate that returns a value which will be checked for uniqueness, or a string that has the name of the property.

Return:

Collection

A collection containing ue values.

Example:

No Arguments
const unique = new Collection([2, 1, 2, 3, 3, 4, 5, 1, 2]).unique();
console.log(unique); // [2, 1, 3, 4, 5]
Property Name
const students = new Collection([
		{ name: 'Rick', grade: 'A'},
		{ name: 'Mick', grade: 'B'},
		{ name: 'Richard', grade: 'A'},
]);
// Students with unique grades.
students.unique('grade'); // [{ name: 'Rick', grade: 'A'}, { name: 'Mick', grade: 'B'}]
With Callback
const students = new Collection([
		{ name: 'Rick', grade: 'A'},
		{ name: 'Mick', grade: 'B'},
		{ name: 'Richard', grade: 'A'},
]);
// Students with unique grades.
students.unique(s => s.grade); // [{ name: 'Rick', grade: 'A'}, { name: 'Mick', grade: 'B'}]

public values(): Collection source

Gets the values without preserving the keys.

Return:

Collection

A Collection containing the values.

Example:

const collection = new Collection({
    1: 2,
    2: 3,
    4: 5
}).values();

console.log(collection.all()); / /[2, 3, 5]

public where(callback: function | string, value: *): Collection source

Filters the collection using a callback or equality comparison to a property in each item.

Params:

NameTypeAttributeDescription
callback function | string

The callback to be used to filter the collection.

value *
  • optional
  • default: null

The value to be compared.

Return:

Collection

A collection with the filtered items.

Example:

Using a property name
const collection = new Collection([
    { name: 'Arya Stark', age: 9 },
    { name: 'Bran Stark', age: 7 },
    { name: 'Jon Snow', age: 14 }
]).where('age', 14);
console.log(collection.all()); // [{ name: 'Jon Snow', age: 14 }]
Using a callback
const collection = new Collection([
    { name: 'Arya Stark', age: 9 },
    { name: 'Bran Stark', age: 7 },
    { name: 'Jon Snow', age: 14 }
]).where(stark => stark.age === 14);
console.log(collection.all()); // [{ name: 'Jon Snow', age: 14 }]

public zip(array: Array | Collection): Collection source

Pairs each item in the collection with another array item in the same index.

Params:

NameTypeAttributeDescription
array Array | Collection

the array to be paired with.

Return:

Collection

A collection with the paired items.

Example:

const array = ['a', 'b', 'c']; // or a collection.
const collection = new Collection([1, 2, 3]).zip(array);
console.log(collection.all()); // [[1, 'a'], [2, 'b'], [3, 'c']]