-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdeque.js
40 lines (33 loc) · 979 Bytes
/
deque.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
// License: CC0 1.0 Universal
// https://www.slideshare.net/catupper/amortize-analysis-of-deque-with-2-stack
class Deque {
constructor() {
this.front = [];
this.back = [];
}
get length() {
return this.front.length + this.back.length;
}
get(index) {
if (index < this.front.length) return this.front[index];
return this.back[this.back.length - 1 - (index - this.front.length)];
}
push_front(...xs) {
this.front.push(...xs);
}
push_back(...xs) {
this.back.push(...xs);
}
pop_front() {
if (this.front.length == 0) this.front = this.back.splice(0, this.back.length + 1 >> 1).reverse();
return this.front.pop();
}
pop_back() {
if (this.back.length == 0) this.back = this.front.splice(0, this.front.length + 1 >> 1).reverse();
return this.back.pop();
}
*[Symbol.iterator]() {
for (const value of this.front) yield value;
for (let i = this.back.length; i--; ) yield this.back[i];
}
}