Skip to content

Instantly share code, notes, and snippets.

@rxluz
Last active January 29, 2019 04:49
Show Gist options
  • Select an option

  • Save rxluz/2a59c2c2f58c360d42f797022bef5b5d to your computer and use it in GitHub Desktop.

Select an option

Save rxluz/2a59c2c2f58c360d42f797022bef5b5d 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 decimalToBinary = num => {
let currentNum = num
let binaryList = new Stack()
let binaryString = ''
if (num === 0) {
return '0'
}
while (currentNum > 0) {
binaryList.push(currentNum % 2)
currentNum = Math.floor(currentNum / 2)
}
while (!binaryList.isEmpty()) {
binaryString += binaryList.pop()
}
return binaryString
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment