coll

0.1.3 • Public • Published

Coll

JavaScript Collection Library for Node.js

Installation

Install with NPM:

$ npm install coll

In your JavaScript:

var coll = require('coll');

The Classes

List

An indexed list of items with functions for manipulating, iterating, searching, indexing, and transforming.

List Constructor

new is optional

var ls1 = new coll.List;
var ls2 = coll.List();
 
ls1 instanceof coll.List; // true
ls2 instanceof coll.List; // true

Accepts any iterable item to initially populate the list. An iterable is most anything with indexes and a length property that can be iterated over.

var ls1 = coll.List([2, 4, 6]);
// ls1 => [2, 4, 5]
 
var ls2 = coll.List('abc');
// ls2 => ['a', 'b', 'c']
 
var ls3 = coll.List(coll.List([true, 2.99]))
// ls3 => [true, 2.99]
 
;(function() {
  var argls = coll.List(arguments);
  // argls => ['hi', true, /foo/]
})('hi', true, /foo/);

List Functions

List.range( start [, end [, step]] )

Returns a List of numbers from start up to and including end. If only start is passed, a list of numbers ranging from 0 through start will be returned. If the optional step parameter is passed, that will be used as the incrementing value. The default increment is 1.

var ls = coll.List.range(-4, 4);
// ls => [-4, -3, -2, -1, 0, 1, 2, 3, 4]
var ls = coll.List.range(3);
// ls => [0, 1, 2, 3]
var ls = coll.List.range(8, 18, 2);
// ls => [8, 10, 12, 14, 16, 18]

List Instance Properties

List#length

Number of items in the list.

var ls = coll.List([2,4,6]);
// ls.length => 3

List Instance Functions

List#get( index [, _default] )

Returns the item at the specifed index. If the index is not present within the list, a RangeError is thrown. If the optional _default value is passed, that will be returned when the index is not present.

var ls = coll.List(['apple', 'orange', 'pear', 'grape']);
var x = ls.get(2);
// x => 'pear'
 
ls.get(37); // throws RangeError
 
= ls.get(37, 'mango');
// x => 'mango'

List#slice( [beginindex [, endindex]] )

Returns a section of the list. Functions the same as Array#slice except this version returns an instance of List.

var ls = coll.List('abcde');
var x = ls.slice(2, 4);
// x  => ['c', 'd']
// ls => ['a', 'b', 'c', 'd', 'e']

List#first( [_default] )

Returns the first item in the list. If the list is empty, undefined is returned. If an optional _default value is passed, that will be returned in the case of an empty list.

var ls = coll.List(['apple', 'orange', 'pear', 'grape']);
var x = ls.first();
// x => 'apple'
var ls = coll.List();
var x = ls.first();
// x => undefined
 
= ls.first('foo');
// x => 'foo'

List#last()

Returns the last item in the list. If the list is empty, undefined is returned. If an optional _default value is passed, that will be returned in the case of an empty list.

var ls = coll.List(['apple', 'orange', 'pear', 'grape']);
var x = ls.last();
// x => 'grape'
var ls = coll.List();
var x = ls.last();
// x => undefined
 
= ls.last('bar');
// x => 'bar'

List#min( [comparer] )

Returns the item with the minimum value from the list.

The optional comparer parameter can be either a function or a string. If it is a function, then it will be used to determine the minimum value. comparer functions work as they do in Array#sort.

If comparer is a string, then it will be assumed that the list is composed of objects and the value to be compared will be that of the property name passed.

var ls = coll.List([4,2,8,5]);
var x = ls.min();
// x => 2
// With optional comparer function
var ls = coll.List(['aaa', 'bb', 'ccccccc', 'dddd']);
var x = ls.min(function(a, b) {
  return a.length - b.length;
});
// x => 'bb'
// With optional comparer property name
var ls = coll.List([
  {foo:34, bar:'erf'},
  {foo:12, bar:'xcv'},
  {foo:45, bar:'bhu'},
  {foo:26, bar:'aer'}
]);
var x = ls.min('bar');
// x => {foo:26, bar:'aer'}

List#max( [comparer] )

Returns the item with the maximum value from the list.

The optional comparer parameter can be either a function or a string. If it is a function, then it will be used to determine the maximum value. comparer functions work as they do in Array#sort.

If comparer is a string, then it will be assumed that the list is composed of objects and the value to be compared will be that of the property name passed.

var ls = coll.List([4,2,8,5]);
var x = ls.max();
// x => 8
// With optional comparer function
var ls = coll.List(['aaa', 'bb', 'ccccccc', 'dddd']);
var x = ls.max(function(a, b) {
  return a.length - b.length;
});
// x => 'ccccccc'
// With optional comparer property name
var ls = coll.List([
  {foo:34, bar:'erf'},
  {foo:12, bar:'xcv'},
  {foo:45, bar:'bhu'},
  {foo:26, bar:'aer'}
]);
var x = ls.max('bar');
// x => {foo:12, bar:'xcv'}

List#set( index, obj )

Set the list item at index to obj.

var ls = coll.List([1,2,3]);
ls.set(1, 99);
// ls => [1, 99, 3]

List#add( item [, itemN] )

Appends one or more items to the end of the list. Returns the list instance.

var ls = coll.List('abc');
ls.add('d');
ls.add('e', 'f');
// ls => ['a', 'b', 'c', 'd', 'e', 'f']

List#addRange( iterable )

Appends a range of new items to the end of the list. Returns the list instance.

var ls = coll.List();
ls.addRange([2,4,6]);
ls.addRange('abc');
// ls => [2, 4, 6, 'a', 'b', 'c']

List#insert( index, item )

Inserts a new item at the specified index. Returns the list instance.

var ls = coll.List('abd');
ls.insert(2, 'c');
// ls => ['a', 'b', 'c', 'd']

List#insertRange( index, iterable )

Inserts a range of new items starting at the specifed index. Returns the list instance.

var ls = coll.List([10,20,30]);
ls.insertRange(1, [12,14]);
// ls => [10, 12, 14, 20, 30]

List#remove( item [, index] )

Removes the first occurence of the passed item in the list. Returns the removed item, or undefined if the item is not in the list. If the optional index parameter is passed, the first matching item after that index will be removed.

var ls = coll.List([1,4,2,6,2,3]);
var x = ls.remove(2);
// x  => 2
// ls => [1, 4, 6, 2, 3]

List#removeFirst()

Removes and returns the first item in the list.

var ls = coll.List(['some', 'text', 'and', 'stuff']);
var x = ls.removeFirst();
// x  => 'some'
// ls => ['text', 'and', 'stuff']

List#removeLast()

Removes and returns the last item in the list.

var ls = coll.List(['some', 'text', 'and', 'stuff']);
var x = ls.removeLast();
// x  => 'stuff'
// ls => ['some', 'text', 'and']

List#removeIf( [context,] iterator )

Removes and returns the first item in the list to pass the iterator function. If no item passes the iterator test, undefined is returned.

var ls = coll.List([2,4,6,7,8]);
var x = ls.removeIf(function(item, index, list) {
  return item % 2 !== 0;
});
// x  => 7
// ls => [2, 4, 6, 8]
 
// With optional context
var obj = {foo:'bar'};
ls.removeIf(obj, function(item, index, list) {
  // this => {foo:'bar'}
});

List#removeAll( [context,] iterator )

Removes every item in the list that passes the iterator test. Returns a new List of the removed items.

var ls = coll.List([1,2,3,4,5,6,7,8]);
var x = ls.removeAll(function(item, index, list) {
  return item % 2 === 0;
});
// x  => [2, 4, 6, 8]
// ls => [1, 3, 5, 7]
 
 
// With optional context
var obj = {foo:'bar'};
ls.removeAll(obj, function(item, index, list) {
  // this => {foo:'bar'}
});

List#removeAt( index [, howmany] )

Removes the item at the given index. Returns the removed item. If the optional howmany parameter is passed, a range of items is removed starting at the index. A new List of the removed items will then be returned.

var ls = coll.List('abcdef');
var x = removeAt(2);
// x  => 'c'
// ls => ['a', 'b', 'd' 'e', 'f']
// With `howmany` parameter
var ls = coll.List('abcdef');
var x = removeAt(2, 3);
// x  => ['c', 'd', 'e']
// ls => ['a', 'b', 'f']

List#clear()

Removes all items from the list. Returns the instance.

var ls = coll.List([1,2,3]);
var x = ls.clear();
// ls => []
=== ls; // true

List#find( [context,] iterator )

Returns the first item in the list to pass the iterator test. If no item passes the iterator test, undefined is returned.

var ls = coll.List(23, '45', Date.now(), 'foo', 99.99, 'bar']);
var x = ls.find(function(item, index, list) {
  return isNaN(item);
});
// x => 'foo'
 
// With optional context
var obj = {foo:'bar'};
ls.find(obj, function(item, index, list) {
  // this => {foo:'bar'}
});

List#findLast( [context,] iterator )

Returns the last item in the list that passes the iterator test. If no item passes the iterator test, undefined is returned.

var ls = coll.List(['aa', 'bb', 'cccccccc', 'dd', 'eeeeee']);
var x = ls.findLast(function(item, index, list) {
  return item.length < 3;
});
// x => 'dd'
 
// With optional context
var obj = {foo:'bar'};
ls.findLast(obj, function(item, index, list) {
  // this => {foo:'bar'}
});

List#findAll( [context,] iterator )

Returns a new List of every item in the instance list that passes the iterator test.

var ls = coll.List(['aa', 'bb', 'cccccccc', 'dd', 'eeeeee']);
var x = ls.findAll(function(item, index, list) {
  return item.length < 3;
});
// x => ['aa', 'bb', 'dd']
 
// With optional context
var obj = {foo:'bar'};
ls.findAll(obj, function(item, index, list) {
  // this => {foo:'bar'}

List#contains( item )

Determines if the passed item is in the list.

var ls = coll.List(['top', 'bottom', 'left']);
ls.contains('left');  // true
ls.contains('right'); // false

List#count( [item] )

Returns the number of occurences of item within the list. If no argument is passed, the list's length is returned.

var ls = coll.List([2,4,2,7,2,8]);
var x = ls.count(2);
// x => 3

List#countIf( [context,] iterator )

Returns the number of occurences that the iterator tests successfully against the items in the list.

var ls = coll.List([1,2,3,4,5,6,7,8,9]);
var x = ls.countIf(function(item, index, list) {
  return item % 2 === 0;
});
// x => 4
 
// With optional context
var obj = {foo:'bar'};
ls.countIf(obj, function(item, index, list) {
  // this => {foo:'bar'}
});

List#filter( [context,] iterator )

Returns a new List composed of items that pass the iterator function.

var ls = coll.List([
  {name:'Jay'}, {name:'Joan'}, {name:'Bob'}, {name:'Flo'}, {name:'Jim'}
]);
var x = ls.filter(function(item, index, list) {
  return item.name[0] === 'J';
});
// x => [
//  {name:'Jay'}, {name:'Joan'}, {name:'Jim'}
// ]
 
// With optional context
var obj = {foo:'bar'};
ls.filter(obj, function(item, index, list) {
  // this => {foo:'bar'}
});

List#reject( [context,] iterator )

Returns a new List composed of items that fail the iterator function.

var ls = coll.List([
  {name:'Jay'}, {name:'Joan'}, {name:'Bob'}, {name:'Flo'}, {name:'Jim'}
]);
var x = ls.reject(function(item, index, list) {
  return item.name[0] === 'J';
});
// x => [
//  {name:'Bob'}, {name:'Flo'}
// ]
 
// With optional context
var obj = {foo:'bar'};
ls.reject(obj, function(item, index, list) {
  // this => {foo:'bar'}
});

List#sort( [comparer] )

Returns a new, sorted List of the instance's items. Numeric items (numbers, dates, booleans) are sorted numerically. Other types are sorted lexicographically.

If a list contains mixed types, the order of sort precedence is:

  1. number literals
  2. string literals
  3. boolean literals
  4. date objects
  5. number objects
  6. string objects
  7. boolean objects
  8. regexes
  9. functions
  10. objects
  11. arrays
  12. global properties (NaN, Infinity, undefined, null)

The optional comparer parameter can be either a function or a string. If it is a function, then it will be used to determine sort order. comparer functions work as they do in Array#sort.

If comparer is a string, then it will be assumed that the list is composed of objects and they will be sorted by the property name passed.

var ls = coll.List([33, 4, 77, 5, 2, 8]);
var x = ls.sort();
// x  => [2, 4, 5, 8, 33, 77]
// Mixed types
var date1 = new Date('2012-06-23')
var date2 = new Date('2000-01-01')
var ls = coll.List(
  [9, 'a', /foo/, true, 0, date1, {a:1}, 'sd', date2, 5, false, '1']
);
var x = ls.sort();
// x =>
//  [0, 5, 9, '1', 'a', 'sd', false, true, date2, date1 /foo/, {a:1}]
// With optional comparer function
var ls = coll.List([33, 4, 77, 5, 2, 8]);
var x = ls.sort(function(a, b) {
  return b - a;
});
// x  => [77, 33, 8, 5, 4, 2]
// With optional comparer property name
var ls = coll.List([
  {foo:34, bar:'erf'},
  {foo:12, bar:'xcv'},
  {foo:45, bar:'bhu'},
  {foo:26, bar:'aer'}
]);
var x = ls.sort('bar');
// x => [
//  {foo:26, bar:'aer'},
//  {foo:45, bar:'bhu'},
//  {foo:34, bar:'erf'},
//  {foo:12, bar:'xcv'}
// ]

List#reverse()

Returns a new List of the instance's items with their order reversed.

var ls = coll.List('abc');
var x = ls.reverse();
// x  => ['c', 'b', 'a']
// ls => ['a', 'b', 'c']

List#concat( iterable [, iterableN] )

Returns a new List composed of the instance list concatenated to one or more passed iterables.

var ls = coll.List([2, true]);
var x = ls.concat('abc', coll.List([0,1,2]), [12.99]);
// x  => [2, true, 'a', 'b', 'c', 0, 1, 2, 12.99]
// ls => [2, true]

List#map( [context,] iterator )

Returns a new List of values determined by the iterator function.

var ls = coll.List([
  {name:'Jay'}, {name:'Joan'}, {name:'Bob'}, {name:'Flo'}, {name:'Jim'}
]);
var x = ls.map(function(item, index, list) {
  return 'User ' + item.name;
});
// x => [
//  'User Jay', 'User Joan', 'User Bob', 'User Flo', 'User Jim'
// ]
 
// With optional context
var obj = {foo:'bar'};
ls.map(obj, function(item, index, list) {
  // this => {foo:'bar'}
});

List#intersperse( obj )

Returns a new List with obj inserted between every item in the list.

var ls = coll.List([1,2,3,4,5]);
var x = ls.intersperse('|');
// x => [
//  1, '|', 2, '|', 3, '|', 4, '|', 5
// ]

List#join( [separator] )

Borrowed from Array#join.

var ls = coll.List([2, 4, 6]);
var x = ls.join();
// x => '2,4,6'
 
= ls.join(' - ');
// x => '2 - 4 - 6'

List#unique()

Returns a new List of non-duplicate items found within the instance list. Duplicates are determines with strict equality.

var ls = coll.List('abcddcba');
var x = ls.unique();
// x => ['a', 'b', 'c', 'd']

List#clean()

Returns a copy of the list with all occurences of undefined, null, and NaN removed.

var ls = coll.List(['a', null, 0, false, undefined, +'foo', 'bar']);
var x = ls.clean();
// x => ['a', 0, false, 'bar']

List#clone()

Returns a copy of the list in a new instance.

var ls = coll.List([2,4]);
var x = ls.clone();
// x  => [2, 4]
// ls => [2, 4]
instanceof coll.List; // true
=== ls;               // false

List#toArray()

Returns a copy of the list's items in an Array.

var ls = coll.List([true, 'fajita', 4.89]);
var x = ls.toArray();
// x => [true, 'fajita', 4.89]
Array.isArray(x); // true;

List#take( howmany )

Returns a new List of the first howmany contiguous items from the instance list.

var ls = coll.List('abcdefg');
var x = ls.take(3);
// x => ['a', 'b', 'c']

List#takeWhile( [context,] iterator )

Returns a new List of contiguous items, starting at the beginning of the list, so long as the iterator function returns true.

var ls = coll.List([4,2,6,3,8,4,2,6]);
var x = ls.takeWhile(function(item, index, list) {
  return item < 8;
});
// x => [4, 2, 6, 3]
 
// With optional context
var obj = {foo:'bar'};
ls.takeWhile(obj, function(item, index, list) {
  // this => {foo:'bar'}
});

List#drop( howmany )

Returns a new List of contiguous items, dropping the first howmany items from the instance list.

var ls = coll.List('abcdefg');
var x = ls.drop(3);
// x => ['d', 'e', 'f', 'g']

List#dropWhile( [context,] iterator )

Returns a new List of contiguous items, starting at the first item in the instance list that fails the passed iterator function.

var ls = coll.List([4,2,6,3,8,4,2,6]);
var x = ls.dropWhile(function(item, index, list) {
  return item < 8;
});
// x => [8, 4, 2, 6]
 
// With optional context
var obj = {foo:'bar'};
ls.dropWhile(obj, function(item, index, list) {
  // this => {foo:'bar'}
});

List#group( [[context,] iterator] )

Returns a hash of sublists, grouped either by equality to each other or by the result of the optional iterator function.

var ls = coll.List([2,3,1,2,2,3]);
var x = ls.group();
// x => {
//  '1' : [1],
//  '2' : [2, 2, 2],
//  '3' : [3, 3]
// }
// With optional iterator function
var ls = coll.List(['#fff', '#3366ee', 'magenta', '#ccc', 'red'])
var hexColorRegex = /^#[abcdef0-9]{3,6}$/i;
var x = ls.group(function(item, index, list) {
  return hexColorRegex.test(item)
    ? 'hex'
    : 'named';
});
// x => {
//  hex   : ['#fff', '#3366ee', '#ccc'],
//  named : ['magenta', 'red']
// }

List#partition( [context,] iterator )

Returns an Array of two Lists. The first list is composed of the items that pass the iterator function. The second list is composed of those items that failed it.

var ls = coll.List([2,4,8,3,6,3,9,0,7]);
var x = ls.partition(function(item, index, list) {
  return item < 5;
});
// x => [
//  [2, 4, 3, 3, 0],
//  [8, 6, 9, 7]
// ]
Array.isArray(x);     // true
x[0] instanceof coll.List; // true
x[1] instanceof coll.List; // true
 
// With optional context
var obj = {foo:'bar'};
ls.partition(obj, function(item, index, list) {
  // this => {foo:'bar'}
});

List#intersect( iterable )

Returns a new List of items present in both the instance list and in the passed iterable.

var ls = coll.List(['apple', 'orange', 'pear', 'grape']);
var x = ls.intersect(['peach', 'pear', 'plum', 'apple', 'mango']);
// x => ['apple', 'pear']

List#difference( iterable )

Returns a new list composed of the list values not present in the passed iterable.

var ls = coll.List(['apple', 'orange', 'pear', 'grape']);
var x = ls.difference(['peach', 'pear', 'plum', 'apple', 'mango']);
// x => ['orange', 'grape']

List#union( iterable )

Returns a new List representing the union of the list and in the passed iterable. That is, the combined unique items between the two.

var ls = coll.List(['apple', 'orange', 'pear', 'grape']);
var x = ls.union(['peach', 'pear', 'plum', 'apple', 'mango']);
// x => ['apple', 'orange', 'pear', 'grape', 'peach', 'plum', 'mango']

List#zip( iterable [, iterableN] )

Returns a new List of Lists by merging values of the instance list with the passed iterables at their corresponding indices.

If passed iterables are shorter than instance list, undefined will be used for missing values. If passed iterables are longer than the instance list, values will be trimmed.

var ls = coll.List(['alpha', 'bravo', 'charlie']);
var x = ls.zip([2, 4, 6]);
// x => [
//   ['alpha',   2],
//   ['bravo',   4],
//   ['charlie', 6]
// ]
// With a shorter iterable passed.
var ls = coll.List(['alpha', 'bravo', 'charlie']);
var x = ls.zip([1,2], 'abc');
// x => [
//   ['alpha',   1,         'a'],
//   ['bravo',   2,         'b'],
//   ['charlie', undefined, 'c']
// ]
// With a longer iterable passed.
var ls = coll.List(['alpha', 'bravo', 'charlie']);
var x = ls.zip([1,2,3,4,5,6], 'abcdefghij');
// x => [
//   ['alpha',   1, 'a'],
//   ['bravo',   2, 'b'],
//   ['charlie', 3, 'c']
// ]

List#indexOf( item [, index] )

Returns the index of the first occurence of item in the list. If item is not found, -1 will be returned. Borrowed from Array#indexOf.

var ls = coll.List([1.99, 8.99, 3.99, 1.99, 7.99, 3.99, 1.99]);
var x = ls.indexOf(3.99);
// x => 2
= ls.indexOf(9.99);
// x => -1

List#lastIndexOf( item [, index] )

Returns the index of the last occurence of item in the list. If item is not found, -1 will be returned. Borrowed from Array#lastIndexOf.

var ls = coll.List([1.99, 8.99, 3.99, 1.99, 7.99, 3.99, 1.99]);
var x = ls.lastIndexOf(3.99);
// x => 5
= ls.lastIndexOf(9.99);
// x => -1

List#indexIf( [index, [context,]] iterator )

Returns the index of the first item in the list that passes the iterator function.

var ls = coll.List([
  {name:'Leo'}, {name:'Jeb'}, {name:'Jojo'}, {name:'Flo'}, {name:'Jojo'}
]);
var x = ls.indexIf(function(item, index, list) {
  return item.name === 'Jojo';
});
// x => 2
// With optional start index
var ls = coll.List([2,3,6,4,7,4,6]);
var x = ls.indexIf(2, function(item, index, list) {
  return item % 2 !== 0;
});
// x => 4
// With optional context
var obj = {foo:'bar'};
ls.indexIf(null, obj, function(item, index, list) {
  // this => {foo:'bar'}
});

List#lastIndexIf( [index, [context,]] iterator )

Returns the index of the last item in the list that passes the iterator function.

var ls = coll.List([
  {name:'Leo'}, {name:'Jeb'}, {name:'Jojo'}, {name:'Flo'}, {name:'Jojo'}
]);
var x = ls.lastIndexIf(function(item, index, list) {
  return item.name === 'Jojo';
});
// x => 4
// With optional start index
var ls = coll.List([2,3,6,4,7,4,6]);
var x = ls.lastIndexIf(3, function(item, index, list) {
  return item % 2 !== 0;
});
// x => 1
// With optional context
var obj = {foo:'bar'};
ls.lastIndexIf(null, obj, function(item, index, list) {
  // this => {foo:'bar'}
});

List#indicesOf( item [, index] )

Returns the indices of every item in the list matching item.

var ls = coll.List('abcaegaatf');
var x = ls.indicesOf('a');
// x => [0, 3, 6, 7]
// With optional index
var ls = coll.List('abcaegaatf');
var x = ls.indicesOf('a', 2);
// x => [3, 6, 7]

List#indicesIf( [index, [context,]] iterator )

Returns the indices of every item in the list that passes the `iterator function.

var ls = coll.List([1,2,3,4,5,6,7]);
var x = ls.indicesIf(function(item, index, list) {
  return item % 2 === 0;
});
// x => [1, 3, 5]
// With optional start index
var ls = coll.List([1,2,3,4,5,6,7]);
var x = ls.indicesIf(2, function(item, index, list) {
  return item % 2 === 0;
});
// x => [3, 5]
// With optional context
var obj = {foo:'bar'};
ls.indicesIf(null, obj, function(item, index, list) {
  // this => {foo:'bar'}
});

List#forEach( [context,] iterator )

Iterates over the items in the list, invoking the passed iterator function for each item. Returns the list instance.

var ls = coll.List(['Taco', 'Burrito', 'Fajita']);
var x = ls.forEach(function(item, index, list) {
  console.log('%d : %s', index, item);
});
// Console output:
//  0 : Taco
//  1 : Burrito
//  2 : Fajita
=== ls; // true
// With optional context
var obj = {foo:'bar'};
ls.forEach(obj, function(item, index, list) {
  // this => {foo:'bar'}
});

List#some( [context,] iterator )

Returns true if at least one item in the list passes the iterator function. Otherwise false is returned.

var ls = coll.List([2,4,6,9,10]);
var x = ls.some(function(item, index, list) {
  return item % 2 !== 0;
});
// x => true
 
= ls.some(function(item, index, list) {
  return item > 50;
});
// x => false
// With optional context
var obj = {foo:'bar'};
ls.some(obj, function(item, index, list) {
  // this => {foo:'bar'}
});

List#every( [context,] iterator )

Returns true if every item in the list passes the iterator test. Otherwise false is returned.

var ls = coll.List([2,4,6,9,10]);
var x = ls.every(function(item, index, list) {
  return item <= 10;
});
// x => true
 
= ls.every(function(item, index, list) {
  return item % 2 === 0;
});
// x => false
// With optional context
var obj = {foo:'bar'};
ls.every(obj, function(item, index, list) {
  // this => {foo:'bar'}
});

List#reduce( [initval,] iterator )

Reduces the list into a single accumulated value. Left to right.

var ls = coll.List([1,2,3]);
var sum = ls.reduce(function(a, b, index, list) {
  return a + b;
});
// sum => 6
var ls = coll.List([3,8,2,5]);
var max = ls.reduce(function(a, b, index, list) {
  return a >= b ? a : b;
});
// max => 8
// With optional initval
var ls = coll.List([1,2,3]);
var x = ls.reduce([], function(arr, b, index, list) {
  arr.push(* 10);
  return arr;
});
// x => [10, 20, 30]

List#reduceRight( [initval,] iterator )

Reduces the list into a single accumulated value. Right to left.

var ls = coll.List('abc');
var x = ls.reduceRight(function(a, b, index, list) {
  return a + b;
});
// x => 'cba'
// With optional initval
var ls = coll.List('abc');
var x = ls.reduceRight('---', function(str, b, index, list) {
  return str + b;
});
// x => '---cba'

Dict

A simple key/value collection, where keys are Strings and values can be any type or object. Keys are unique within the collection.

Dict Constructor

new is optional

var d1 = new coll.Dict;
var d2 = coll.Dict();
 
d1 instanceof coll.Dict; // true
d2 instanceof coll.Dict; // true

Accepts an object literal to initially populate the dict.

var d = coll.Dict({a:10, b:20});
// d => {a:10, b:20}

Dict Instance Properties

Dict#length

The number of items in the dict.

var d = coll.Dict({a:2, b:4, c:6});
// d.length => 3

Dict#keys

An array of the dict's keys. Order is arbitrary.

var d = coll.Dict({name:'Fred', age:5000, town:'Bedrock'});
// d.keys => ['name', 'age', 'town']

Dict#values

An array of the dict's values. Order is arbitrary.

var d = coll.Dict({name:'Fred', age:5000, town:'Bedrock'});
// d.values => ['Fred', 5000, 'Bedrock']

Dict Instance Functions

Dict#haskey( key )

Returns true if key exists within the dict. Otherwise false is returned.

var d = coll.Dict({name:'Fred', age:5000, town:'Bedrock'});
d.hasKey('town');    // true
d.hasKey('address'); // false

Dict#get( key [, _default] )

Returns the value for key. If an optional _default value is passed, that will be returned in cases where the key does not exist within the dict. If key does not exist within the dict and _default is not passed, a ReferenceError is thrown.

var d = coll.Dict({name:'Fred', age:5000, town:'Bedrock'});
var x = d.get('town');
// x => 'Bedrock'
 
= d.get('occupation', 'excavator');
// x => 'excavator'
 
d.get('occupation'); // throws ReferenceError

Dict#set( key, value )

Set value value for key key. If the key already exists in the dict then it's value will be overwritten. If the key does not exist, then it will be added. Returns the instance.

var d = coll.Dict();
var x = d.set('volume', .92);
// d => {volume: .92}
=== d; // true
 
d.set('volume', .85);
// d => {volume: .85}

Dict#add( hash [, hashN] )

Adds one or more key/value pairs to the dict. Returns the instance.

var d = coll.Dict();
d.add({a:'alpha', b:'bravo'});
d.add({c:'charlie'}, {d:'delta', e:'echo'}, {f:'foxtrot'});
// d => {
//  a:'alpha', b:'bravo', c:'charlie', d:'delta', e:'echo', f:'foxtrot'
// }

Dict#remove( key )

Removes a key/value pair from the collection by key and returns the removed value. If key does not exist within the dict a ReferenceError is thrown.

var d = coll.Dict({name:'Fred', age:5000, town:'Bedrock'});
var x = d.remove('town');
// x => 'Bedrock'
// d => {name:'Fred', age:5000}
 
d.remove('occupation'); // throws ReferenceError

Dict#clear()

Removes all key/value pairs from the dict. Returns the instance.

var d = coll.Dict({name:'Fred', age:5000, town:'Bedrock'});
var x = d.clear();
// d => {}
=== d; // true

Dict#forEach( [context,] iterator )

Iterates over the dict, calling the iterator function for each key/value pair. Returns the instance.

var d = coll.Dict({name:'Fred', age:5000, town:'Bedrock'});
var x = d.forEach(function(key, value, dict) {
  console.log('Key: %s, Val: %s', key, value);
});
// Output:
//  Key: name, Val: Fred
//  Key: age, Val: 5000
//  Key: town, Val: Bedrock
=== d; // true
// With optional context
var obj = {foo:'bar'};
d.forEach(obj, function(key, value, dict) {
  // this => {foo:'bar'}
});

Dict#some( [context,] iterator )

Returns true if at least one key/value pair in the dict passes the iterator function. Otherwise false is returned.

var d = coll.Dict();
d.set('Creep',            {year:1993, album:'Pablo Honey'});
d.set('Paranoid Android', {year:1997, album:'OK Computer'});
d.set('Karma Police',     {year:1997, album:'OK Computer'});
var x = d.some(function(key, value, dict) {
  return value.year > 1996;
});
// x => true
// With optional context
var obj = {foo:'bar'};
d.some(obj, function(key, value, dict) {
  // this => {foo:'bar'}
});

Dict#every( [context,] iterator )

Returns true if every key/value pair in the dict passes the iterator function. Otherwise false is returned.

var d = coll.Dict();
d.set('Creep',            {year:1993, album:'Pablo Honey'});
d.set('Paranoid Android', {year:1997, album:'OK Computer'});
d.set('Karma Police',     {year:1997, album:'OK Computer'});
var x = d.every(function(key, value, dict) {
  return value.album === 'OK Computer';
});
// x => false
// With optional context
var obj = {foo:'bar'};
d.every(obj, function(key, value, dict) {
  // this => {foo:'bar'}
});

Dict#filter( [context,] iterator )

Returns a new Dict composed of key/value pairs that pass the iterator function.

var d = coll.Dict();
d.set('Creep',            {year:1993, album:'Pablo Honey'});
d.set('Paranoid Android', {year:1997, album:'OK Computer'});
d.set('Karma Police',     {year:1997, album:'OK Computer'});
var x = d.filter(function(key, value, dict) {
  return value.album === 'OK Computer';
});
// x => {
//  'Paranoid Android' : {year:1997, album:'OK Computer'},
//  'Karma Police'     : {year:1997, album:'OK Computer'}
// }
// With optional context
var obj = {foo:'bar'};
d.filter(obj, function(key, value, dict) {
  // this => {foo:'bar'}
});

Dict#reject( [context,] iterator )

Returns a new Dict composed of key/value pairs that fail the iterator function.

var d = coll.Dict();
d.set('Creep',            {year:1993, album:'Pablo Honey'});
d.set('Paranoid Android', {year:1997, album:'OK Computer'});
d.set('Karma Police',     {year:1997, album:'OK Computer'});
var x = d.reject(function(key, value, dict) {
  return value.album === 'OK Computer';
});
// x => {
//  'Creep' : {year:1993, album:'Pablo Honey'},
// }
// With optional context
var obj = {foo:'bar'};
d.reject(obj, function(key, value, dict) {
  // this => {foo:'bar'}
});

Dict#clone()

Returns a copy of the dict in a new instance.

var d = coll.Dict({a:2, b:4});
var x = d.clone();
// x => {a:2, b:4}
// d => {a:2, b:4}
instanceof coll.Dict; // true
=== d;                // false

Dict#fill( defaults )

Returns a new Dict with the holes in the instance collection filled by the those defined in defaults. defaults can be an object literal or another Dict.

// Example: Day calendar of schedule openings, 9am to 2pm
var defaultSchedule = {
  '9:00 am'  : 'unavailable',
  '10:00 am' : 'unavailable',
  '11:00 am' : 'unavailable',
  '12:00 pm' : 'unavailable',
  '1:00 pm'  : 'unavailable',
  '2:00 pm'  : 'unavailable'
}
var openings = coll.Dict({
  '10:00 am' : 'open',
  '11:00 am' : 'open',
  '1:00 pm'  : 'open'
});
 
var sched = openings.fill(defaultSchedule);
// sched => {
//   '9:00 am'  : 'unavailable',
//   '10:00 am' : 'open',
//   '11:00 am' : 'open',
//   '12:00 pm' : 'unavailable',
//   '1:00 pm'  : 'open',
//   '2:00 pm'  : 'unavailable'
// }

Dict#toLiteral( [serializer] )

Returns the key/value pairs of the dict as an object literal. If the optional serializer function is passed, that will be used to determine the key.

var d = coll.Dict({a:10, b:20, c:30});
var obj = d.toLiteral();
// obj => {a:10, b:20, c:30}
for (var key in obj) {
  console.log('%s : %s', key, obj[key]);
}
// Output:
//  a : 10
//  b : 20
//  c : 30
// With optional serializer
var d = coll.Dict({a:10, b:20, c:30});
var obj = d.toLiteral(function(key, value) {
  return key.toUpperCase();
});
// obj => {A:10, B:20, C:30}

Dict#toArray()

Returns the dict's key/value pairs in an array of 'tuples'.

var d = coll.Dict({a:10, b:20, c:30});
var x = d.toArray();
// x => [['a', 10], ['b', 20], ['c', 30]]

Map

A key/value collection, where both keys and values can be any object or type. Keys are unique within the collection by strict equality.

Map Constructor

new is optional

var m1 = new coll.Map;
var m2 = coll.Map();
 
m1 instanceof coll.Map; // true
m2 instanceof coll.Map; // true

Accepts an array of key/value pairs ('tuples') to initially populate the map.

var m = coll.Map([['a', 10], [/foo/i, 20]]);
// m => {
//  'a'    => 10,
//  /foo/i => 20
// }

Map Instance Properties

Map#length

The number of items in the map.

var m = coll.Map([['a', 10], [/foo/i, 20]]);
// m.length => 2

Map#keys

An array of the map's keys. Order is arbitrary.

var m = coll.Map([[{a:1}, 'dog'], [{b:2}, 'cat'], [23.389, 'rock']]);
// m.keys => [{a:1}, {b:2}, 23.389]

Map#values

An array of the dict's values. Order is arbitrary.

var m = coll.Map([[{a:1}, 'dog'], [{b:2}, 'cat'], [23.389, 'rock']]);
// m.values => ['dog', 'cat', 'rock']

Map Instance Functions

Map#haskey( key )

Returns true if key exists within the map. Otherwise false is returned. Keys are determined and are unique by strict equality.

var m = coll.Map();
var key1 = {a:1};
var key2 = /foo/i;
m.set(key1, 'a');
m.set(key2, 'b');
m.set(9999, 'c');
 
m.hasKey(key1);   // true
m.hasKey({a:1});  // false
m.hasKey(key2);   // true
m.hasKey(/foo/i); // false
m.hasKey(9999);   // true

Map#get( key [, _default] )

Returns the value for key. If an optional _default value is passed, that will be returned in cases where the key does not exist within the map. If key does not exist within the map and _default is not passed, a ReferenceError is thrown. Keys are determined and are unique by strict equality.

var m = coll.Map();
var key1 = /foo/gi;
m.set(key1, 'stuff');
m.set(23.89, 'thing');
 
var x = m.get(key1);
// x => 'stuff'
= m.get(23.89);
// x => 'thing'
 
= m.get(/bar/gi, 'nada');
// x => 'nada'
 
m.get(77.11);   // throws ReferenceError
m.get(/foo/gi); // throws ReferenceError

Map#set( key, value )

Set value value for key key. If the key already exists in the map then it's value will be overwritten. If the key does not exist, then it will be added. Returns the instance.

var m = coll.Map();
var x = m.set('volume', .92);
// m => {
//  'volume' => .92
// }
=== d; // true
 
d.set('volume', .85);
// m => {
//  'volume' => .85
// }

Map#remove( key )

Removes a key/value pair from the collection by key and returns the removed value. If key does not exist within the map a ReferenceError is thrown.

var m = coll.Map();
var key1 = {name:'Jen'};
var key2 = {name:'Tim'};
m.set(key1, 83.234);
m.set(key2, 72.183);
m.set('yo', 14.384);
 
var x = m.remove(key2);
// x => 72.183
// m => {
//  {name:'Jen'} => 83.234,
//  'yo'         => 14.384
// }
 
m.remove('hi');         // throws ReferenceError
m.remove({name:'Jen'}); // throws ReferenceError

Map#clear()

Removes all key/value pairs from the map. Returns the instance.

var m = coll.Map([[/yo/, 'joe'], [new Date, 123]]);
var x = m.clear();
// m => {}
=== m; // true

Map#forEach( [context,] iterator )

Iterates over the map, calling the iterator function for each key/value pair. Returns the instance.

var m = coll.Map();
m.set(new Date(2012, 4, 5),  'Cinco de Mayo');
m.set(new Date(2012, 3, 17), 'Taxes!!');
m.set(new Date(2012, 9, 31), 'Halloween');
 
var x = m.forEach(function(key, value, map) {
  console.log('Key: %s, Val: %s', key.toDateString(), value);
});
// Output:
//  Key: Sat May 05 2012, Val: Cinco de Mayo
//  Key: Tue Apr 17 2012, Val: Taxes!!
//  Key: Wed Oct 31 2012, Val: Halloween
=== m; // true
// With optional context
var obj = {foo:'bar'};
m.forEach(obj, function(key, value, dict) {
  // this => {foo:'bar'}
});

Map#some( [context,] iterator )

Returns true if at least one key/value pair in the map passes the iterator function. Otherwise false is returned.

var m = coll.Map();
m.set(new Date(2011, 9, 31), 'Halloween');
m.set(new Date(2012, 4, 5),  'Cinco de Mayo');
m.set(new Date(2012, 3, 17), 'Taxes!!');
m.set(new Date(2012, 9, 31), 'Halloween');
 
var x = m.some(function(key, value, dict) {
  return value !== 'Halloween' && key.getFullYear() === 2012;
});
// x => true
// With optional context
var obj = {foo:'bar'};
m.some(obj, function(key, value, dict) {
  // this => {foo:'bar'}
});

Map#every( [context,] iterator )

Returns true if every key/value pair in the map passes the iterator function. Otherwise false is returned.

var m = coll.Map();
m.set(new Date(2011, 9, 31), 'Halloween');
m.set(new Date(2012, 4, 5),  'Cinco de Mayo');
m.set(new Date(2012, 3, 17), 'Taxes!!');
m.set(new Date(2012, 9, 31), 'Halloween');
 
var x = m.every(function(key, value, dict) {
  return key.getFullYear() === 2012;
});
// x => false
 
= m.every(function(key, value, dict) {
  return key.getFullYear() > 2010;
});
// x => true
// With optional context
var obj = {foo:'bar'};
m.every(obj, function(key, value, dict) {
  // this => {foo:'bar'}
});

Map#filter( [context,] iterator )

Returns a new Map composed of key/value pairs that pass the iterator function.

var m = coll.Map();
m.set(new Date(2011, 9, 31), 'Halloween');
m.set(new Date(2012, 0, 1),  'New Years');
m.set(new Date(2012, 4, 5),  'Cinco de Mayo');
m.set(new Date(2012, 3, 17), 'Taxes!!');
m.set(new Date(2012, 9, 31), 'Halloween');
 
var x = m.filter(function(key, value, dict) {
  return key.getMonth() >= 3 && value !== 'Taxes!!';
});
// x => {
//  Mon Oct 31 2011 => 'Halloween',
//  Sat May 05 2012 => 'Cinco de Mayo',
//  Wed Oct 31 2012 => 'Halloween'
// }
// With optional context
var obj = {foo:'bar'};
m.filter(obj, function(key, value, dict) {
  // this => {foo:'bar'}
});

Map#reject( [context,] iterator )

Returns a new Map composed of key/value pairs that fail the iterator function.

var m = coll.Map();
m.set(new Date(2011, 9, 31), 'Halloween');
m.set(new Date(2012, 0, 1),  'New Years');
m.set(new Date(2012, 4, 5),  'Cinco de Mayo');
m.set(new Date(2012, 3, 17), 'Taxes!!');
m.set(new Date(2012, 9, 31), 'Halloween');
 
var x = m.reject(function(key, value, dict) {
  return key.getMonth() > 3;
});
// x => {
//  Sun Jan 01 2012 => 'New Years'
//  Tue Apr 17 2012 => 'Taxes!!'
// }
// With optional context
var obj = {foo:'bar'};
m.reject(obj, function(key, value, dict) {
  // this => {foo:'bar'}
});

Map#clone()

Returns a copy of the map in a new instance.

var m = coll.Map([[{a:1}, 11], [{b:2}, 22]]);
var x = m.clone();
 
// x => {
//  {a:1} => 11,
//  {b:2} => 22
// }
// m => {
//  {a:1} => 11,
//  {b:2} => 22
// }
instanceof coll.Map; // true
=== m;               // false

Map#fill( defaults )

Returns a new Map with the holes in the instance collection filled by the those defined in defaults. defaults can be an Array of tuples or another Map.

// Example: Day calendar of schedule openings, 9am to 2pm
var defaultSchedule = [
  ['9:00 am',  'unavailable'],
  ['10:00 am', 'unavailable'],
  ['11:00 am', 'unavailable'],
  ['12:00 pm', 'unavailable'],
  ['1:00 pm',  'unavailable'],
  ['2:00 pm',  'unavailable']
];
var openings = coll.Map([
  ['10:00 am', 'open'],
  ['11:00 am', 'open'],
  ['1:00 pm',  'open']
]);
 
var sched = openings.fill(defaultSchedule);
// sched => {
//   '9:00 am'  => 'unavailable',
//   '10:00 am' => 'open',
//   '11:00 am' => 'open',
//   '12:00 pm' => 'unavailable',
//   '1:00 pm'  => 'open',
//   '2:00 pm'  => 'unavailable'
// }

Map#toLiteral( [serializer] )

Returns the key/value pairs of the map as an object literal. If the optional serializer function is passed, that will be used to determine the key.

If your map keys are not strings, numbers, or anything that would not automatically convert (toString()) to a unique key string, it is highly recommended that you provide a serializer function. Otherwise you will risk losing key/value pairs due to key collision and/or the keys produced may not be that descriptive.

var m = coll.Map();
var key1 = {position:'rb', team:'Vikings'};
var key2 = {position:'wr', team:'Cardinals'};
var key3 = {position:'ss', team:'Steelers'};
m.set(key1, 'Peterson');
m.set(key2, 'Fitz');
m.set(key3, 'Polamalu');
 
var x = m.toLiteral(function(key, val) {
  return key.team + ':' + key.position;
});
// x => {
//  'Vikings:rb':   'Peterson',
//  'Cardinals:wr': 'Fitz',
//  'Steelers:ss':  'Polamalu'
// }
for (var key in x) {
  console.log('%s : %s', key, x[key]);
}
// Output:
//  Vikings:rb : Peterson
//  Cardinals:wr : Fitz
//  Steelers:ss : Polamalu
 
// Without serializer function
= m.toLiteral();
// x => {'[object Object]': 'Polamalu'}

Map#toArray()

Returns the map's key/value pairs in an array of 'tuples'.

var m = coll.Map();
var key1 = {position:'rb', team:'Vikings'};
var key2 = {position:'wr', team:'Cardinals'};
var key3 = {position:'ss', team:'Steelers'};
m.set(key1, 'Peterson');
m.set(key2, 'Fitz');
m.set(key3, 'Polamalu');
 
var x = m.toArray();
// x => [
//  [{position:'rb', team:'Vikings'},   'Peterson'],
//  [{position:'wr', team:'Cardinals'}, 'Fitz'],
//  [{position:'ss', team:'Steelers'},  'Polamalu']
// ]

Readme

Keywords

none

Package Sidebar

Install

npm i coll

Weekly Downloads

2

Version

0.1.3

License

none

Last publish

Collaborators

  • corymartin