/queue

:package: A highly performant queue implementation in javascript.

Primary LanguageJavaScriptMIT LicenseMIT

@datastructures-js/queue

build:? npm npm npm

A highly performant queue implementation in javascript.

Table of Contents

Install

npm install --save @datastructures-js/queue

API

require

const Queue = require('@datastructures-js/queue');

import

import Queue from '@datastructures-js/queue';

Construction

using "new Queue(array)"

Example
// empty queue
const queue = new Queue();

// from an array
const queue = new Queue([1, 2, 3]);

using "Queue.fromArray(array)"

Example
// empty queue
const queue = Queue.fromArray([]);

// with elements
const list = [10, 3, 8, 40, 1];
const queue = Queue.fromArray(list);

// If the list should not be mutated, simply construct the queue from a copy of it.
const queue = Queue.fromArray(list.slice(0));

.enqueue(element)

adds an element at the back of the queue.

params
nametype
elementobject
runtime
O(1)

Example

queue.enqueue(10);
queue.enqueue(20);

.front()

peeks on the front element of the queue.

return
object
runtime
O(1)

Example

console.log(queue.front()); // 10

.back()

peeks on the back element in the queue.

return
object
runtime
O(1)

Example

console.log(queue.back()); // 20

.dequeue()

dequeue the front element in the queue. It does not use .shift() to dequeue an element. Instead, it uses a pointer to get the front element and only remove elements when reaching half size of the queue.

return
object
runtime
O(n*log(n))

Example

console.log(queue.dequeue()); // 10
console.log(queue.front()); // 20

Dequeuing all elements takes O(n*log(n)) instead of O(n2) if using shift().

Here's a benchmark:

dequeuing 1 million elements in Node v12
.dequeue().shift()
~ 40 ms~ 3 minutes

.isEmpty()

checks if the queue is empty.

return
boolean
runtime
O(1)

Example

console.log(queue.isEmpty()); // false

.size()

returns the number of elements in the queue.

return
number
runtime
O(1)

Example

console.log(queue.size()); // 1

.clone()

creates a shallow copy of the queue.

return
Queue
runtime
O(n)

Example

const queue = Queue.fromArray([{ id: 2 }, { id: 4 } , { id: 8 }]);
const clone =  queue.clone();

clone.dequeue();

console.log(queue.front()); // { id: 2 }
console.log(clone.front()); // { id: 4 }

.toArray()

returns a copy of the remaining elements as an array.

return
array
runtime
O(n)

Example

queue.enqueue(4);
queue.enqueue(2);
console.log(queue.toArray()); // [20, 4, 2]

.clear()

clears all elements from the queue.

runtime
O(1)

Example

queue.clear();
queue.size(); // 0

Build

lint + tests

grunt build

License

The MIT License. Full License is here