Step by Step implementation of Deque
Step 1: Define a Deque Class using a constructor function, in which we initialise properties of object that will be created when Deque class is instantiated. Here, we have initialised an array inside constructor that we will be using throughout to store elements.
class Deque {
constructor() {
this.deque = [];
}
}
Step 2: Create a function – addFront() that takes an element as an argument to be inserted from front of the deque. Using unshift() JavaScript method, element will be added in the front.
addFront(element) {
this.deque.unshift(element);
}
Step 3: Create a function – addRear() that takes an “element” as an argument to be added at the end of deque. Using push() method element will be added at rear of deque array.
addRear(element) {
this.deque.push(element);
}
Step 4: Create a function isEmpty() that checks if deque is not empty, because there should be at least one element from deque to remove.
isEmpty() {
return this.deque.length === 0;
}
Step 5: Create a function removeFront() to remove an element from front if deque is not empty otherwise return null.
removeFront() {
if (!this.isEmpty()) {
return this.deque.shift();
}
return null;
}
Step 6: Create another function removeRear() that first checks if deque is not empty, then it removes element from the rear(end) of deque or returns null if deque array is empty.
removeRear() {
if (!this.isEmpty()) {
return this.deque.pop();
}
return null;
}
Step 7: Create getFront() function that returns first element from deque if its not empty.
getFront(){
if(!this.isEmpty()){
return this.deque[0];
}
return null;
}
Step 8: Create a getRear() function that returns last element from deque. We access the last element from deque using index-method, “size() -1 ” returns last index of deque, then element at last index is accessed and returned.
getRear(){
if(!this.isEmpty()){
return this.deque[this.size()-1]
}
return null;
}
Step 9: Create a size() function that returns the length of the deque.
size() {
return this.deque.length;
}