sameer karjatkar
sameer karjatkar

Reputation: 2057

Defining a queue datastructure in JavaScript

I am just trying to learn JavaScript. I want to design a queue which takes the following format:

[{(0,0),0}], [{(0,1),1}], [{(0,2),2}]

So I tried to define the queue in the following way, but obviously it's not correct

var queue = [{}] ;

Upvotes: 1

Views: 123

Answers (3)

Ayush Sharma
Ayush Sharma

Reputation: 1

You can build queue as follows:

function Queue () {
 this.dataStore = [];
 this.enqueue = enqueue;
 this.dequeue = dequeue;
 this.front = front;
 this.back = back;
 this.toString = toString;
 this.empty = empty;
}

// Insetion
function enqueue(element){
 this.dataStore.push(element);
}

// Deletion
function dequeue(){
 this.dataStore.shift();
}

// front
function front(){
 return this.dataStore[0];
}

//back
function back(){
 return this.dataStore[this.dataStore.length-1];
}

//toString
function toString(){
  var retStr = '';
  for(var i = 0; i < this.dataStore.length; i++){
    retStr = retStr + this.dataStore[i]
  }
  return retStr;
 }

//empty
function empty(){
 if(this.dataStore.length === 0) {
  return true;
 }
 return false;
}

Now use it as a constructor method, var q = new Queue().

Upvotes: 0

mariusnn
mariusnn

Reputation: 1897

For the queue you want to use an array for keeping the values

var myQueue = []  //Empty array

Add something to the queue by pushing it onto the array

myQueue.push(new Person(...))

Fetch something from the queue by shifting it out of the array

var nextInLine = myQueue.shift()

Upvotes: 2

Julien Lafont
Julien Lafont

Reputation: 7877

Firstly, there is no "couple" data-strucuture in JS, so your (0,1) must be an array [0,1] , an object: {x: 0, y: 1} or a custom type (see below).

In javascript, structures aren't strongly typed, so you just have to define if the root is an array or an object. In this case, it seems to be an array.

var queue = [];

Then, push in the queue what you need. For example : (I invented the field names, fits them to your use case)

var element1 = {coords: [0, 0], val: 0 };
queue.push(element1);
var element2 = {coords: [0, 1], val: 1 };
queue.push(element2);

Like I said, you can use another representation, like: [[0,0], 0], or define a custom type (Object-oriented).

function MyType(coords, val) {
  this.coords = coords;
  this.val = val;
}

function Couple(x, y) {
  this.x = x;
  this.y = y;
}

queue.push(new MyType(new Couple(1, 2), 3))

Upvotes: 5

Related Questions