# Mnemonist

## Queue

A queue is simply a list in First In First Out (FIFO) order.

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

If you know the maximum number of items your queue will need to store, you should check the `CircularBuffer` structure for better performance.

``````const Queue = require('mnemonist/queue');
``````

## Use case

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

``````const queue = new Queue();
queue.enqueue(tree.root);

while (queue.size) {
const node = queue.dequeue();
console.log('Traversed node:', node);

node.children.forEach((child) => {
queue.enqueue(child);
});
}
``````

## Constructor

The `Queue` takes no argument.

### Static #.from

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

``````const queue = Queue.from([1, 2, 3]);
``````

### Static #.of

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

``````const queue = Queue.of(1, 2, 3);
``````

## Methods

Mutation

Iteration

### #.size

Number of items in the queue.

``````const queue = new Queue();
queue.size
>>> 0
``````

### #.enqueue

Adds an item to the queue.

`O(1)`

``````const queue = new Queue();

queue.enqueue(1);
``````

### #.dequeue

Retrieve & remove the next item of the queue.

`O(1) amortized`

``````const queue = new Queue();

queue.enqueue(1);
queue.dequeue();
>>> 1
``````

Completely clears the queue.

``````const queue = new Queue();

queue.enqueue(1);
queue.clear();
queue.toArray();
>>> []
``````

### #.peek

Retrieves the next item of the queue.

`O(1)`

``````const queue = new Queue();

queue.enqueue(1);
queue.peek();
>>> 1
``````

### #.forEach

Iterates over the queue in FIFO order.

``````const queue = new Queue();

queue.enqueue(1);
queue.enqueue(2);

queue.forEach((item, index, queue) => {
console.log(index, item);
});
``````

### #.toArray

Converts the queue into a FIFO JavaScript array.

``````const queue = new Queue();

queue.enqueue(1);
queue.enqueue(2);

queue.toArray();
>>> [1, 2]
``````

### #.values

Returns an iterator over the queue’s values.

``````const queue = Queue.from([1, 2, 3]);

const iterator = queue.values();

iterator.next().value
>>> 1
``````

### #.entries

Returns an iterator over the queue’s entries.

``````const queue = Queue.from([1, 2, 3]);

const iterator = queue.entries();

iterator.next().value
>>> [0, 1]
``````

### Iterable

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

``````const queue = Queue.from([1, 2, 3]);

for (const item of queue) {
console.log(item);
}
``````