Last active
January 29, 2019 04:48
-
-
Save rxluz/4e0d92985db02ecf9244df2fbb890e1d to your computer and use it in GitHub Desktop.
JS Data Structures: Stacks, see more at: https://medium.com/p/7dcea711c091
This file contains hidden or 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
function Stack() { | |
let items = [] | |
class PublicStack { | |
peek() { | |
if (this.isEmpty()) throw new Error('Stack is empty') | |
const lastItemIndex = items.length - 1 | |
return items[lastItemIndex] | |
} | |
pop() { | |
if (this.isEmpty()) throw new Error('Stack is empty') | |
return items.pop() | |
} | |
push(data) { | |
items.push(data) | |
} | |
isEmpty() { | |
return this.size() === 0 | |
} | |
size() { | |
return items.length | |
} | |
} | |
return new PublicStack() | |
} | |
const reverseString = currentString => { | |
let stringLettersStack = new Stack() | |
let stringLetters = '' | |
for (let index = 0; index < currentString.length; index++) { | |
stringLettersStack.push(currentString[index]) | |
} | |
while (!stringLettersStack.isEmpty()) { | |
stringLetters += stringLettersStack.pop() | |
} | |
return stringLetters | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment