Package Exports
- @datastructures-js/queue
This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (@datastructures-js/queue) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.
Readme
@datastructures-js/queue
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';
Create a Queue
empty queue
const queue = new Queue();
// OR
const queue = Queue.fromArray([]);
from an existing array
runtime | params |
---|---|
O(1) | list: {array<object>} |
const list = [10, 3, 8, 40, 1];
const queue = new Queue(list);
// OR
const queue = Queue.fromArray(list);
If the list should not be mutated, simply construct the queue from a copy of it.
const queue = new Queue(list.slice(0));
.enqueue(element)
adds an element at the back of the queue.
runtime | params |
---|---|
O(1) | element: {object} |
queue.enqueue(10);
queue.enqueue(20);
.front()
peeks on the front element of the queue.
runtime | return |
---|---|
O(1) | {object} |
console.log(queue.front()); // 10
.back()
peeks on the back element in the queue.
runtime | return |
---|---|
O(1) | {object} |
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 an offset to get the front element and only remove elements when reaching half size of the queue.
runtime | return |
---|---|
O(1) / O(n/2k) | {object} |
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.
runtime | return |
---|---|
O(1) | {boolean} |
console.log(queue.isEmpty()); // false
.size()
returns the number of elements in the queue.
runtime | return |
---|---|
O(1) | {number} |
console.log(queue.size()); // 1
.clone()
creates a shallow copy of the queue.
runtime | return |
---|---|
O(n) | {Queue} |
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.
runtime | return |
---|---|
O(n) | {array} |
queue.enqueue(4);
queue.enqueue(2);
console.log(queue.toArray()); // [20, 4, 2]
.clear()
clears all elements from the queue.
runtime |
---|
O(1) |
queue.clear();
queue.size(); // 0
Build
lint + tests
grunt build
License
The MIT License. Full License is here