Mnemonist

Stack

A stack is simply a list in Last In First Out (LIFO) order.

This just means that inserted items will get out in the reversed insertion order.

Note that if you know the maximum size your stack will have and if you want a more performant stack implementation, you can check the FiniteStack.

var Stack = require('mnemonist/stack');

Use case

A stack is really useful to perform, for instance, the depth-first traversal of a tree:

var stack = new Stack();
stack.push(tree.root);

while (stack.size) {
var node = stack.pop();
console.log('Traversed node:', node);

node.children.forEach(function(child) {
stack.push(child);
});
}

Constructor

The Stack takes no argument.

Static #.from

Alternatively, one can build a Stack from an arbitrary JavaScript iterable likewise:

var stack = Stack.from([1, 2, 3]);

Static #.of

You can also build a Stack from an arbitrary set of arguments:

var stack = Stack.of(1, 2, 3);

Methods

Mutation

Iteration

#.size

Number of items in the stack.

var stack = new Stack();
stack.size
>>> 0

#.push

Adds an item to the stack.

O(1)

var stack = new Stack();

stack.push(1);

#.pop

Retrieve & remove the next item of the stack.

O(1)

var stack = new Stack();

stack.push(1);
stack.pop();
>>> 1

Completely clears the stack.

O(1)

var stack = new Stack();

stack.push(1);
stack.clear();
stack.toArray();
>>> []

#.peek

Retrieves the next item of the stack.

O(1)

var stack = new Stack();

stack.push(1);
stack.peek();
>>> 1

#.forEach

Iterates over the stack in LIFO order.

var stack = new Stack();

stack.push(1);
stack.push(2);

stack.forEach(function(item, index, stack) {
console.log(index, item);
});

#.toArray

Converts the stack into a LIFO JavaScript array.

var stack = new Stack();

stack.push(1);
stack.push(2);

stack.toArray();
>>> [2, 1]

#.values

Returns an iterator over the stack’s values.

var stack = Stack.from([1, 2, 3]);

var iterator = stack.values();

iterator.next().value
>>> 3

#.entries

Returns an iterator over the stack’s entries.

var stack = Stack.from([1, 2, 3]);

var iterator = stack.entries();

iterator.next().value
>>> [0, 3]

Iterable

Alternatively, you can iterate over a stack’s values using ES2015 for...of protocol:

var stack = Stack.from([1, 2, 3]);

for (var item of stack) {
console.log(item);
}