Skip to content

Instantly share code, notes, and snippets.

@helderberto
Created December 6, 2020 16:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save helderberto/ba99b60ddedf0a24f79fe042253deb4d to your computer and use it in GitHub Desktop.
Save helderberto/ba99b60ddedf0a24f79fe042253deb4d to your computer and use it in GitHub Desktop.
JavaScript: Stack Data Structure
class Stack {
constructor() {
this.items = [];
}
push(elements) {
this.items.push(elements);
}
pop() {
return this.items.pop();
}
peek() {
return this.items[this.items.length - 1];
}
isEmpty() {
return this.items.length === 0;
}
clear() {
this.items = [];
}
size() {
return this.items.length;
}
toString() {
return this.items.toString();
}
}
const books = new Stack();
books.push("The Hobbit");
books.push("LOTR: The Fellowship of the Ring");
books.push("LOTR: The Two Towers");
books.push("LOTR: The Return of the King");
console.log(books.peek()); // => "LOTR: The Return of the King"
books.pop();
books.pop();
console.log(books.toString()); // => "The Hobbit,LOTR: The Fellowship of the Ring"
console.log(books.size()); // => 2
books.clear();
console.log(books.isEmpty()); // => true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment