Skip to content

Instantly share code, notes, and snippets.

@bschandramohan
Created June 16, 2014 18:17
Show Gist options
  • Select an option

  • Save bschandramohan/64a06bdd5dfbd9999702 to your computer and use it in GitHub Desktop.

Select an option

Save bschandramohan/64a06bdd5dfbd9999702 to your computer and use it in GitHub Desktop.
Queue implementation in javascript
/**
* Queue Implementation in Javascript
* @param name
* @constructor
*/
function Queue(name) {
/**
* Name to just indicate the name of the current instance. Just for debugging purpose and doesn't have any effect
* on the working of the Queue.
* NOTE: Feel free to not pass this parameter.
*/
this._name = name;
/**
* Array to store the data
* @type {Array}
*/
this._internalArray = [];
/**
* Front Index where the element is inserted
* @type {number}
*/
this._front = 0;
/**
* Read Index where the element is deleted
* @type {number}
*/
this._rear = -1;
}
Queue.prototype = {
_getDataStoreElement: function (index) {
return this._internalArray[index];
},
_setDataStoreElement: function (index, val) {
this._internalArray[index] = val;
},
insert: function (val) {
console.log("Queue[" + this._name + "] insert called with val:" + val);
this._setDataStoreElement(this._front, val);
this._front++;
if (this._rear <= -1) {
this._rear = 0;
}
},
remove: function () {
if (this._rear <= -1) {
console.log("No elements in queue");
}
console.log("Element removed is" + this._getDataStoreElement(this._rear));
this._rear++;
},
print: function () {
if (this._rear <= -1) {
console.log("Empty Queue!");
return;
}
var printMessage = "Elements of Queue [" + this._name + "] are: [";
for (var i = this._rear; i < this._front; i++) {
printMessage += this._getDataStoreElement(i) + ",";
}
printMessage += "]";
console.log(printMessage);
}
};
// TEST CODE
var myQueue = new Queue("myQueue");
myQueue.insert("1");
myQueue.insert("2");
myQueue.print();
myQueue.remove();
myQueue.print();
var myQueue2 = new Queue("myQueue2");
myQueue2.insert(109);
myQueue2.insert(3);
myQueue2.remove();
myQueue2.print();
myQueue2.insert(4);
myQueue2.print();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment