-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathjavascript-deque.js
48 lines (39 loc) · 1.26 KB
/
javascript-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
41
42
43
44
45
46
47
48
/* Deque data structure in javascript / js */
class Deque {
values = [];
constructor(values) {
if (values) this.values = values; // no copy
// if (values) this.values = [...values]; // copy
}
get length() {
return this.size();
}
size = () => this.values.length;
isEmpty = () => this.size() === 0;
back = () => this.values[this.size() - 1];
push_back = (x) => this.values.push(x);
pop_back = () => this.values.pop();
front = () => this.values[0];
push_front = (x) => this.values.unshift(x); // to be tested
pop_front = () => this.values.shift();
}
function use() {
let q = new Deque();
q.push_back(10);
q.push_back(20);
console.log(q.size()); // 2 // output
console.log(q.isEmpty()); // false
console.log(q.front()); // 10
console.log(q.back()); // 20
console.log(q.pop_front()); // 10
console.log(q.size()); // 1
console.log(q.isEmpty()); // false
console.log(q.front()); // 20
console.log(q.back()); // 20
console.log(q.pop_back()); // 20
console.log(q.size()); // 0
console.log(q.isEmpty()); // true
console.log(q.front()); // undefined
console.log(q.back()); // undefined
}
use();