A library implementing various data structures in Javascript. Decomposed into AMD modules. Can be used as individual pieces, or all in one piece.
The library so far contains constructors for the following structures:
- Iterable
- Stacks
- Queues
- Doubly Linked Lists
- Heaps
- Union-Find
- Binary Search Trees
- Red-Black trees
- Sorting Algorithms
- Algorithms dealing with graphs
The Iterable mixin is a set of methods for manipulating "iterable objects". For the purposes of the mixin, an iterable object needs to have an iterator
function, which when called returns an object with two methods, next
and done
. Most mixin methods return an iterable object. A toArray
method returns an array from an iterable.
forEach(fun)
callsfun
for each 'element' of the iterable.map(fun)
passes the iterable's values throughfun
. Returns an iterable.toArray()
returns an array of the values in the iterable.foldl(fun)
performs afold left
. The function needs to have signaturefun(acc, item)
.foldr(fun)
performs afold right
. The function needs to have signaturefun(item, acc)
.take(n)
returns the firstn
elements of the iterable, as an iterable.skip(n)
skips the firstn
elements of the iterable. Returns an iterable.slice(a, b)
skips the firsta
elements, then returns all elements until we've exceeded a total of b elements. E.g. slice(2, 5) will return the 2nd through 4th elements.
The Iterable mixing also comes with a constructor to build an iterable object out of an array or an iterator
function, and also comes with built-in class methods for constructing standard (possibly infinite) iterable objects (for example the sequence 1,2,3,...).
Implemented in Stack.js, Stacks use a doubly-linked list to provide a standard stack interface. All methods except iteration take constant time. The following methods are implemented:
push(item)
pushes the item at the top of the stack.pushAll(array)
push all items from the array at the top of the stack. Anything with aforEach
method would do.pop()
removes and returns the item at the top of the stack.peek()
returns the item at the top of the stack, without removing it.isEmpty()
returnstrue
if and only if the stack has no items.processAll(fun)
iterates over the elements in the stack, callingfun
on each. The elements are removed at the same time, resulting in an empty stack.iterator()
returns an iterator for the stack, which allows usage of the Iterable mixin
var Stack = require('Stack.js'),
stack = new Stack();
stack.pushAll([1,2,3]);
stack.push(4);
stack.pop(); // ----> 4
stack.peek(); // ----> 3 but does not remove it
stack.each(console.log); // ----> 3 2 1