-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathFixedCapacityStackOfString.js
55 lines (52 loc) · 1.18 KB
/
FixedCapacityStackOfString.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
class FixedCapacityStackOfString {
constructor(capacity) {
this.s = new Array(capacity);
this.pointer = -1;
this.capacity = capacity;
}
isEmpty() {
return this.pointer === -1;
}
resize(capacity) {
// Create as per new size
const arr = new Array(capacity);
// copy old item to new array
for (let i=0; i <= this.pointer; i++) {
arr[i] = this.s[i];
}
// replace original arr
this.s = arr;
this.capacity = capacity;
}
push(item) {
if (this.pointer >= this.capacity - 1) {
this.resize(this.capacity * 2);
}
this.s[++this.pointer] = item;
}
pop() {
if (this.counter === -1) {
return null;
}
const isResizeNeeded = Math.floor(this.capacity/4) === this.pointer;
if(isResizeNeeded) {
this.resize(Math.floor(this.capacity/2))
}
const value = this.s[this.pointer];
delete this.s[this.pointer];
this.pointer--;
return value;
}
}
const test = () => {
const stack = new FixedCapacityStackOfString(5);
for(let i=0; i < 40; i++) {
stack.push(i);
}
console.log({ stack });
for(let i=0; i < 30; i++) {
stack.pop();
}
console.log({ stack });
};
test();