Last active
September 11, 2021 19:45
-
-
Save netanel-haber/a8f237b2ecbbf6355ce81502672be260 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class MaxStack { | |
stack = []; | |
checkMaxStack(popped) { | |
if (this.max === popped) | |
this.stack.pop(); | |
} | |
feedMaxStack(values) { | |
const largest = Math.max(...values); | |
if (!this.max) { | |
return this.stack.push(largest); | |
} | |
if (largest > this.max) { | |
this.stack.push(largest); | |
} | |
} | |
get max() { | |
return this.stack[this.stack.length - 1]; | |
} | |
} | |
class Stack { | |
stack = []; | |
#maxStack = new MaxStack(); | |
constructor(...values) { | |
this.push(...values) | |
} | |
push(...values) { | |
this.#maxStack.feedMaxStack(values); | |
return this.stack.push(...values); | |
} | |
pop() { | |
const popped = this.stack.pop(); | |
this.#maxStack.checkMaxStack(popped); | |
return popped; | |
} | |
get max() { | |
return this.#maxStack.max; | |
} | |
toString() { | |
const largest = this.max; | |
let mostDigits = this.stack.reduce((max, cur) => Math.max(String(cur).length, max), 0) + 2; | |
const bottomOfTheBarrel = ` ${"▔".repeat(mostDigits)}`; | |
const stringifiedStack = this.stack.map((v) => { | |
const currentDigits = String(v).length; | |
const leftSpacing = Math.floor(mostDigits / 2) - Math.floor(currentDigits / 2); | |
const rightSpacing = mostDigits - leftSpacing - currentDigits; | |
const largestPointer = v === largest ? "<- largest" : ""; | |
return `|${" ".repeat(leftSpacing)}${v}${" ".repeat(rightSpacing)}| ${largestPointer}`; | |
}).reverse().join("\n"); | |
return `\n${stringifiedStack}\n${bottomOfTheBarrel}`; | |
} | |
} | |
const stack = new Stack(50,80,20,50,1,2); | |
console.clear(); | |
actions = [["push", 20], ["push", 90], ["push", 2], ["pop"], ["pop"]]; | |
actions.reduce((acc, [act, val]) => { | |
return acc.then(() => { | |
stack[act](val); | |
console.log(String(stack)); | |
return new Promise((res) => { | |
setTimeout(() => { | |
console.clear(); | |
res(); | |
}, 2000) | |
}) | |
}) | |
}, Promise.resolve()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment