Created
December 25, 2017 04:33
-
-
Save nickangtc/79e49eb723a3a91ddd62f38563361add to your computer and use it in GitHub Desktop.
Simple implementation of a Queue in JavaScript - with performance tests
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* ============================================ | |
* 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