Created
December 6, 2020 16:10
-
-
Save helderberto/ba99b60ddedf0a24f79fe042253deb4d to your computer and use it in GitHub Desktop.
JavaScript: Stack Data Structure
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 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