Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adds Queue in JavaScript. -> Queue/Queue.js #175

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
63 changes: 63 additions & 0 deletions Queue/Queue.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
// class definition
class Queue {
constructor(size) {
this.size = size;
this.data = [];
}

// checks if Queue is empty
isEmpty() {
return this.data.length === 0;
}

// checks if Queue is full
isFull() {
return this.data.length === this.size;
}

// Inserts element at the last of the Queue
enQueue(element) {
if (!this.isFull()) {
this.data.push(element);
} else {
throw Error("Queue overflow.");
}
}

// Removes first element from the Queue.
deQueue() {
if (this.isEmpty()) {
throw Error("Queue underflow.");
} else {
return this.data.shift();
}
}

// Peek at the front of the Queue. This doesn't remove element from the Queue;
front() {
if (this.isEmpty()) {
console.log("Queue is empty.");
} else {
return this.data[0];
}
}

// To print the Queue data.
printQueue() {
console.log(this.data);
}
}


// Usage
const q = new Queue(5);
q.enQueue(1); // [1]
q.enQueue(2); // [1, 2]
q.enQueue(3); // [1, 2, 3]
q.enQueue(4); // [1, 2, 3, 4]
q.enQueue(5); // [1, 2, 3, 4, 5]
q.front(); // 1
q.deQueue(); // 5
q.enQueue(5); // [1, 2, 3, 4, 5]
q.printQueue(); // prints the Queue data.
q.enQueue(6); // Queue Overflow Error