-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLargestInStack.js
More file actions
77 lines (63 loc) · 1.43 KB
/
LargestInStack.js
File metadata and controls
77 lines (63 loc) · 1.43 KB
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
// Create a Stack class and use it to implement another class that finds
// the largest value in a stack.
// Constraints: Time complexity of O(1)
'use strict';
const expect = require('expect');
const regularStack = function() {
this.storage = {};
this.count = 0;
this.push = (val) => {
this.storage[this.count] = val;
this.count++;
};
this.pop = () => {
let popped = this.storage[this.count-1];
delete this.storage[this.count-1];
this.count--;
return popped;
};
this.size = () => {
return Object.keys(this.storage).length;
};
this.peek = () => {
if(this.storage[this.count-1]){
return this.storage[this.count-1];
}
else{
return false;
}
};
};
const maxStack = function() {
this.firstStorage = new regularStack();
this.maxStorage = new regularStack();
this.push = (val) => {
this.firstStorage.push(val);
if(val > this.maxStorage.peek()) {
this.maxStorage.push(val);
}
};
this.pop = () => {
let popped = this.firstStorage.pop();
if(popped === this.maxStorage.peek()){
this.maxStorage.pop();
}
return popped;
};
this.getMax = () => {
return this.maxStorage.peek();
};
};
const testFunction = () => {
let test1 = new maxStack();
test1.push(50);
test1.push(53);
test1.push(32);
test1.push(999999);
test1.pop();
expect(
test1.getMax()
).toEqual(53);
};
testFunction();
console.log('All tests passed');