coll v0.1.3
Coll
JavaScript Collections for Node.js
API should be considered alpha and subject to change.
Installation
Install with NPM:
$ npm install collIn your JavaScript:
var List = require('coll').List;
var Dict = require('coll').Dict;
var Map = require('coll').Map;The Classes
- List
- List Creation
- List Constructor
- List.range
- Properties
- List#length
- Accessor Functions
- List#get
- List#slice
- List#first
- List#last
- List#min
- List#max
- Mutator Functions
- List#set
- List#add
- List#addRange
- List#insert
- List#insertRange
- List#remove
- List#removeFirst
- List#removeLast
- List#removeIf
- List#removeAll
- List#removeAt
- List#clear
- Search Functions
- List#find
- List#findLast
- List#findAll
- List#contains
- List#count
- List#countIf
- List#filter
- List#reject
- Transformation Functions
- List#sort
- List#reverse
- List#concat
- List#map
- List#intersperse
- List#join
- List#unique
- List#clean
- List#clone
- List#toArray
- Sub-List Functions
- List#take
- List#takeWhile
- List#drop
- List#dropWhile
- List#group
- List#partition
- List#intersect
- Indexing Functions
- List#indexOf
- List#lastIndexOf
- List#indexIf
- List#lastIndexIf
- List#indicesOf
- List#indicesIf
- Iteration Functions
- List#forEach
- List#some
- List#every
- List#reduce
- List#reduceRight
- Dict
- Dict Creation
- Dict Constructor
- Properties
- Dict#length
- Dict#keys
- Dict#values
- Accessor Functions
- Dict#hasKey
- Dict#get
- Mutator Functions
- Dict#set
- Dict#add
- Dict#remove
- Dict#clear
- Iteration Functions
- Dict#forEach
- Dict#some
- Dict#every
- Search Functions
- Dict#filter
- Dict#reject
- Transformation Functions
- Dict#clone
- Dict#toLiteral
- Dict#toArray
- Map
- Map Creation
- Map Constructor
- Properties
- Map#length
- Map#keys
- Map#values
- Accessor Functions
- Map#hasKey
- Map#get
- Mutator Functions
- Map#set
- Map#remove
- Map#clear
- Iteration Functions
- Map#forEach
- Map#some
- Map#every
- Search Functions
- Map#filter
- Map#reject
- Transformation Functions
- Map#clone
- Map#toLiteral
- Map#toArray
List
An indexed list of items with functions for manipulating, iterating, searching, indexing, and transforming.
List Constructor
new is optional
var ls1 = new List;
var ls2 = List();
ls1 instanceof List; // true
ls2 instanceof List; // trueAccepts 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 = List([2, 4, 6]);
// ls1 => [2, 4, 5]
var ls2 = List('abc');
// ls2 => ['a', 'b', 'c']
var ls3 = List(List([true, 2.99]))
// ls3 => [true, 2.99]
;(function() {
var argls = 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 = List.range(-4, 4);
// ls => [-4, -3, -2, -1, 0, 1, 2, 3, 4]var ls = List.range(3);
// ls => [0, 1, 2, 3]var ls = 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 = List([2,4,6]);
// ls.length => 3List Instance Functions
List#get( index )
Returns the item at the specifed index.
var ls = List(['apple', 'orange', 'pear', 'grape']);
var x = ls.get(2);
// x => 'pear'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 = List('abcde');
var x = ls.slice(2, 4);
// x => ['c', 'd']
// ls => ['a', 'b', 'c', 'd', 'e']List#first()
Returns the first item in the list.
If the list is empty, undefined is returned.
var ls = List(['apple', 'orange', 'pear', 'grape']);
var x = ls.first();
// x => 'apple'List#last()
Returns the last item in the list.
If the list is empty, undefined is returned.
var ls = List(['apple', 'orange', 'pear', 'grape']);
var x = ls.last();
// x => 'grape'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 = List([4,2,8,5]);
var x = ls.min();
// x => 2// With optional comparer function
var ls = 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 = 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 = List([4,2,8,5]);
var x = ls.max();
// x => 8// With optional comparer function
var ls = 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 = 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 = 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 = 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 = 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 = 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 = 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 = 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 = 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 = 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 = 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 = 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 = List('abcdef');
var x = removeAt(2);
// x => 'c'
// ls => ['a', 'b', 'd' 'e', 'f']// With `howmany` parameter
var ls = 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 = List([1,2,3]);
var x = ls.clear();
// ls => []
x === ls; // trueList#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 = 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 = 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 = 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 = List(['top', 'bottom', 'left']);
ls.contains('left'); // true
ls.contains('right'); // falseList#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 = List([2,4,2,7,2,8]);
var x = ls.count(2);
// x => 3List#countIf( context, iterator )
Returns the number of occurences that the iterator tests successfully against
the items in the list.
var ls = 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 = 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 = 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:
- number literals
- string literals
- boolean literals
- date objects
- number objects
- string objects
- boolean objects
- regexes
- functions
- objects
- arrays
- 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 = 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 = 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 = 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 = 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 = 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 = List([2, true]);
var x = ls.concat('abc', 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 = 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 = 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 = List([2, 4, 6]);
var x = ls.join();
// x => '2,4,6'
x = 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 = 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 = 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 = List([2,4]);
var x = ls.clone();
// x => [2, 4]
// ls => [2, 4]
x instanceof List; // true
x === ls; // falseList#toArray()
Returns a copy of the list's items in an Array.
var ls = 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 = 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 = 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 = 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 = 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 = 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 = 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 = 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 List; // true
x[1] instanceof 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 = List(['apple', 'orange', 'pear', 'grape']);
var x = ls.intersect(['peach', 'pear', 'plum', 'apple', 'mango']);
// x => ['apple', 'pear']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 = List([1.99, 8.99, 3.99, 1.99, 7.99, 3.99, 1.99]);
var x = ls.indexOf(3.99);
// x => 2
x = ls.indexOf(9.99);
// x => -1List#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 = List([1.99, 8.99, 3.99, 1.99, 7.99, 3.99, 1.99]);
var x = ls.lastIndexOf(3.99);
// x => 5
x = ls.lastIndexOf(9.99);
// x => -1List#indexIf( [index, context,] iterator )
Returns the index of the first item in the list that passes the iterator
function.
var ls = 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 = 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 = 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 = 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 = List('abcaegaatf');
var x = ls.indicesOf('a');
// x => [0, 3, 6, 7]// With optional index
var ls = 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 = 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 = 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 = 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
x === 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 = List([2,4,6,9,10]);
var x = ls.some(function(item, index, list) {
return item % 2 !== 0;
});
// x => true
x = 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 = List([2,4,6,9,10]);
var x = ls.every(function(item, index, list) {
return item <= 10;
});
// x => true
x = 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 = List([1,2,3]);
var sum = ls.reduce(function(a, b, index, list) {
return a + b;
});
// sum => 6var ls = 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 = List([1,2,3]);
var x = ls.reduce([], function(arr, b, index, list) {
arr.push(b * 10);
return arr;
});
// x => [10, 20, 30]List#reduceRight( initval, iterator )
Reduces the list into a single accumulated value. Right to left.
var ls = List('abc');
var x = ls.reduceRight(function(a, b, index, list) {
return a + b;
});
// x => 'cba'// With optional initval
var ls = 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 Dict;
var d2 = Dict();
d1 instanceof Dict; // true
d2 instanceof Dict; // trueAccepts an object literal to initially populate the dict.
var d = Dict({a:10, b:20});
// d => {a:10, b:20}Dict Instance Properties
Dict#length
The number of items in the dict.
var d = Dict({a:2, b:4, c:6});
// d.length => 3Dict#keys
An array of the dict's keys. Order is arbitrary.
var d = 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 = 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 = Dict({name:'Fred', age:5000, town:'Bedrock'});
d.hasKey('town'); // true
d.hasKey('address'); // falseDict#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 = Dict({name:'Fred', age:5000, town:'Bedrock'});
var x = d.get('town');
// x => 'Bedrock'
x = d.get('occupation', 'excavator');
// x => 'excavator'
d.get('occupation'); // throws ReferenceErrorDict#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 = Dict();
var x = d.set('volume', .92);
// d => {volume: .92}
x === 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 = 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 = Dict({name:'Fred', age:5000, town:'Bedrock'});
var x = d.remove('town');
// x => 'Bedrock'
// d => {name:'Fred', age:5000}
d.remove('occupation'); // throws ReferenceErrorDict#clear()
Removes all key/value pairs from the dict. Returns the instance.
var d = Dict({name:'Fred', age:5000, town:'Bedrock'});
var x = d.clear();
// d => {}
x === d; // trueDict#forEach( context, iterator )
Iterates over the dict, calling the iterator function for
each key/value pair. Returns the instance.
var d = 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
x === 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 = 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 = 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 = 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 = 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 = Dict({a:2, b:4});
var x = d.clone();
// x => {a:2, b:4}
// d => {a:2, b:4}
x instanceof Dict; // true
x === d; // falseDict#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 = 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 = 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 = 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 Map;
var m2 = Map();
m1 instanceof Map; // true
m2 instanceof Map; // trueAccepts an array of key/value pairs ('tuples') to initially populate the map.
var m = 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 = Map([['a', 10], [/foo/i, 20]]);
// m.length => 2Map#keys
An array of the map's keys. Order is arbitrary.
var m = 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 = 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 = 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); // trueMap#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 = Map();
var key1 = /foo/gi;
m.set(key1, 'stuff');
m.set(23.89, 'thing');
var x = m.get(key1);
// x => 'stuff'
x = m.get(23.89);
// x => 'thing'
x = m.get(/bar/gi, 'nada');
// x => 'nada'
m.get(77.11); // throws ReferenceError
m.get(/foo/gi); // throws ReferenceErrorMap#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 = Map();
var x = m.set('volume', .92);
// m => {
// 'volume' => .92
// }
x === 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 = 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 ReferenceErrorMap#clear()
Removes all key/value pairs from the map. Returns the instance.
var m = Map([[/yo/, 'joe'], [new Date, 123]]);
var x = m.clear();
// m => {}
x === m; // trueMap#forEach( context, iterator )
Iterates over the map, calling the iterator function for
each key/value pair. Returns the instance.
var m = 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
x === 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 = 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 = 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
x = 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 = 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 = 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 = 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
// }
x instanceof Map; // true
x === m; // falseMap#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 = 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
x = m.toLiteral();
// x => {'[object Object]': 'Polamalu'}Map#toArray()
Returns the map's key/value pairs in an array of 'tuples'.
var m = 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']
// ]