Skip to content

Instantly share code, notes, and snippets.

@chengsieuly
Last active September 6, 2016 21:00
Show Gist options
  • Save chengsieuly/19c0996c624473f88f99af58cee46513 to your computer and use it in GitHub Desktop.
Save chengsieuly/19c0996c624473f88f99af58cee46513 to your computer and use it in GitHub Desktop.
Deque()
// Less optimal implementation
class Deque {
constructor() {
this.deque = [];
}
addToFront(item) {
this.deque.unshift(item);
}
addToRear(item) {
this.deque.push(item);
}
removeFromFront() {
return this.deque.shift();
}
removeFromRear() {
return this.deque.pop();
}
peekFront() {
if (this.deque.length < 1) throw "Deque is empty";
return this.deque[0];
}
peekRear() {
if (this.deque.length < 1) throw "Deque is empty";
return this.deque[this.deque.length - 1];
}
size() {
return this.deque.length;
}
isEmpty() {
return this.deque.length < 1;
}
}
// More optimal implementation
// Let's add a method to our Queue class
Queue.prototype.pop = function() {
return this.queue.pop();
}
class Deque {
constructor() {
// Separate "front" and "rear"
this.front = new Queue();
this.rear = new Queue();
}
addToFront(item) {
this.front.enqueue(item);
}
addToRear(item) {
this.rear.enqueue(item);
}
removeFromFront() {
if (this.front.isEmpty()) {
if (this.rear.isEmpty()) throw "Deque is empty";
return this.rear.dequeue();
}
return this.front.pop();
}
removeFromRear() {
if (this.rear.isEmpty()) {
if (this.front.isEmpty()) throw "Deque is empty";
return this.front.dequeue();
}
return this.rear.pop();
}
peekFront() {
if (this.front.isEmpty()) {
if (this.rear.isEmpty()) throw "Deque is empty";
return this.rear.peek();
}
return this.front.queue[this.front.size() - 1];
}
peekRear() {
if (this.rear.isEmpty()) {
if (this.front.isEmpty()) throw "Deque is empty";
return this.front.peek();
}
return this.rear.queue[this.rear.size() - 1];
}
size() {
return this.front.size() + this.rear.size();
}
isEmpty() {
return this.front.isEmpty() && this.rear.isEmpty();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment