javascript deque

Solutions on MaxInterview for javascript deque by the best coders in the world

showing results for - "javascript deque"
Ivy
12 Jun 2017
1class Deque {
2    constructor() {
3        this.front = this.back = undefined;
4    }
5    addFront(value) {
6        if (!this.front) this.front = this.back = { value };
7        else this.front = this.front.next = { value, prev: this.front };
8    }
9    removeFront() {
10        let value = this.peekFront();
11        if (this.front === this.back) this.front = this.back = undefined;
12        else (this.front = this.front.prev).next = undefined;
13        return value;
14    }
15    peekFront() { 
16        return this.front && this.front.value;
17    }
18    addBack(value) {
19        if (!this.front) this.front = this.back = { value };
20        else this.back = this.back.prev = { value, next: this.back };
21    }
22    removeBack() {
23        let value = this.peekBack();
24        if (this.front === this.back) this.front = this.back = undefined;
25        else (this.back = this.back.next).back = undefined;
26        return value;
27    }
28    peekBack() { 
29        return this.back && this.back.value;
30    }
31}
32
33// demo
34let deque = new Deque;
35console.log(deque.peekFront()); // undefined
36deque.addFront(1);
37console.log(deque.peekBack()); // 1
38deque.addFront(2);
39console.log(deque.removeBack()); // 1
40deque.addFront(3);
41deque.addFront(4);
42console.log(deque.peekBack()); // 2
43deque.addBack(5);
44deque.addBack(6);
45console.log(deque.peekBack()); // 6
46console.log(deque.removeFront()); // 4
47console.log(deque.removeFront()); // 3
48console.log(deque.removeFront()); // 2
49console.log(deque.removeFront()); // 5
50console.log(deque.removeFront()); // 6
51console.log(deque.removeFront()); // undefined