-
Notifications
You must be signed in to change notification settings - Fork 270
/
Copy pathindex.js
85 lines (68 loc) · 1.36 KB
/
index.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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
/**
* Revision to PR #35 where I implemented bullshit thinking of
* new breakthrough :D
*/
class TwoStacks {
constructor(capacity) {
this.data = [];
this.top1 = -1;
this.top2 = capacity;
this.overflow = new Error('Overflow: Stack is full');
this.capacity = capacity;
}
push1(value) {
if (this.top1 < this.top2 - 1) {
this.top1 += 1;
this.data[this.top1] = value;
} else {
throw this.overflow;
}
}
push2(value) {
if (this.top1 < this.top2 - 1) {
this.top2 -= 1;
this.data[this.top2] = value;
} else {
throw this.overflow;
}
}
pop1() {
if (this.top1 >= 0) {
const item = this.data[this.top1];
delete this.data[this.top1];
this.top1 -= 1;
return item;
}
return -1;
}
pop2() {
if (this.top2 < this.capacity) {
const item = this.data[this.top2];
delete this.data[this.top2];
this.top2 += 1;
return item;
}
return -1;
}
}
module.exports = TwoStacks;
/** Test cases */
/*
const s = new TwoStacks(4);
s.push1('a');
console.log(s.data);
s.push2('a2');
console.log(s.data);
s.push1('b');
console.log(s.data);
s.push2('b2');
console.log(s.data);
s.push2('d2');
console.log(s.data);
s.push2('c23');
console.log(s.data);
console.log(s.pop2());
console.log(s.data);
console.log(s.pop1());
console.log(s.data);
*/