Skip to content

Instantly share code, notes, and snippets.

@nickangtc

nickangtc/queue.js

Created Dec 25, 2017
Embed
What would you like to do?
Simple implementation of a Queue in JavaScript - with performance tests
/**
* ============================================
* CUSTOM IMPLEMENTATION OF QUEUE CLASS
* ============================================
*/
/**
* Implementation of Queue.
*/
class Queue {
/**
* Create a queue.
*/
constructor () {
this.store = {};
this.front = 0;
this.end = 0;
}
}
/**
* Add item to end of queue.
* @param {*} The data to store in the position.
*/
Queue.prototype.enqueue = function (data) {
this.store[this.end] = data;
this.end++;
};
/**
* Remove item from queue and return its data.
* @return {*} The data stored in item.
*/
Queue.prototype.dequeue = function () {
if (this.front === this.end) return null;
const data = this.store[this.front];
delete this.store[this.front];
this.front++;
return data;
};
/**
* Return current size of queue.
* @return {number} Size of queue.
*/
Queue.prototype.size = function () {
return this.end - this.front;
};
/**
* Return item at front of queue without dequeueing.
* @return {*} The data stored in item.
*/
Queue.prototype.peek = function () {
if (this.size() === 0) return null;
return this.store[this.front];
};
/**
* ============================================
* PERFORMANCE TESTING (SPEED)
* ============================================
* Tests by enqueuing `iterations` number of items
* and dequeueing for every multiple of 10.
*/
// Comment out and test accordingly
// const iterations = 10000;
const iterations = 100000;
// Using Queue class implementation
var t0 = performance.now();
const customQueue = new Queue();
for (var i = 0; i < iterations; i++) {
customQueue.enqueue(i);
if (i % 10 === 0) customQueue.dequeue();
}
var t1 = performance.now();
console.log('customQueue performance:', t1 - t0, 'ms');
// Using native Array
var t2 = performance.now();
const arrayQueue = [];
for (var j = 0; j < iterations; j++) {
arrayQueue.push(j);
if (j % 10 === 0) arrayQueue.shift();
}
var t3 = performance.now();
console.log('arrayQueue performance:', t3 - t2, 'ms');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment