Skip to content

Instantly share code, notes, and snippets.

@rxluz
Last active January 29, 2019 04:48
Show Gist options
  • Save rxluz/4e0d92985db02ecf9244df2fbb890e1d to your computer and use it in GitHub Desktop.
Save rxluz/4e0d92985db02ecf9244df2fbb890e1d to your computer and use it in GitHub Desktop.
JS Data Structures: Stacks, see more at: https://medium.com/p/7dcea711c091
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