Queue FIFO - First in, first out - Node.js Data Structure

Node.js examples for Data Structure:Queue

Description

Queue FIFO - First in, first out

Demo Code


/*/* w w  w.j a  va  2  s.co  m*/

QUEUE

Abstract data type
FIFO - First in, first out
Collection of elements with enqueue and dequeue operations.
Note that there is a natural order. Elements are removed in the reverse order of their addition.

DO NOT use an array and the native push/shift method in your implementation. Use an object as the underlying data structure.


*** Operations:

myQueue.enqueue(value)
=> count of queue
add value to collection

myQueue.dequeue()
=> oldest element added collection
Remove item so that it is no longer in collection

myQueue.peek()
=> oldest element added collection
Similiar to dequeue, but do not remove element from collection

myQueue.count()
=> number of elements in queue


*** Additional Exercises:

Modify your queue to take a max capacity and return a string if you try to add an element when there's no more room:
myQueue.enqueue(value)
=> "Max capacity already reached. Remove element before adding a new one."

Create a contains method to check if a value is in the queue:
myQueue.contains('findme')
=> true/false
What's the time complexity?

Create an until method to get the number of dequeues until you get to a certain value:
queue values - (first)2-5-7-3-6-9(last)
myQueue.until(7)
=> 3
What's the time complexity?




 */

function Queue(capacity) {
  // implement me...
  this.storage = {};
  this.size = 0;
  this.firstValueIndex = 1;
}

Queue.prototype.enqueue = function(value) {
  // implement me...
  this.size++;
  this.storage[this.size] = value;
  return this.size;
};
// Time complexity: O(1) constant

Queue.prototype.dequeue = function() {
  // implement me...
  if(this.size > 0) {
    this.size--;
    var removedValue = this.storage[this.firstValueIndex];
    delete this.storage[this.firstValueIndex];
    this.firstValueIndex++;
    return removedValue;
  }
};
// Time complexity: O(1) constant

Queue.prototype.peek = function() {
  // implement me...
  return this.storage[this.firstValueIndex];
};
// Time complexity: O(1) constant

Queue.prototype.count = function() {
  // implement me...
  return this.size;
};
// Time complexity:


var queue = new Queue();
console.log(queue.enqueue('purple'));
console.log(queue.enqueue('green'));
console.log(queue.enqueue('blue'));
console.log(queue.enqueue('silver'));
console.log(queue.enqueue('gold'));
console.log(queue.dequeue());
console.log(queue.storage);
console.log(queue.count());
console.log(queue.peek());
console.log(queue.dequeue());
console.log(queue.storage);
console.log(queue.count());

Related Tutorials