Skip to content

Instantly share code, notes, and snippets.

@nfroidure
Last active December 31, 2018 16:39
Show Gist options
  • Save nfroidure/5472493 to your computer and use it in GitHub Desktop.
Save nfroidure/5472493 to your computer and use it in GitHub Desktop.
A simple Javascript Stack based on an Array wrap. More explanations here : https://insertafter.com/blog-fifo_lifo_javascript.html
class Stack {
constructor(...elements) {
// Initializing the stack with given arguments
this.elements = [...elements];
}
// Proxying the push/shift methods
push(...args) {
return this.elements.push(...args);
}
pop(...args) {
return this.elements.pop(...args);
}
// Add some length utility methods
getLength(...args) {
return this.elements.length;
}
setLength(length) {
return this.elements.length = length;
}
}
const s = new Stack(0,1);
s.push(2);
console.log(s.getLength()); // 3
while(s.getLength())
console.log(s.pop()); // 2, 1, 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment