Skip to content

Instantly share code, notes, and snippets.

@julien-f
Last active December 24, 2021 14:11
Show Gist options
  • Save julien-f/d9394b1b0ab0623e5c4787f7852e7113 to your computer and use it in GitHub Desktop.
Save julien-f/d9394b1b0ab0623e5c4787f7852e7113 to your computer and use it in GitHub Desktop.
// based on implementation in https://github.com/ForbesLindesay/throat
export class Queue {
#head // stack to push to, reverse order
#tail = [] // stack to pop from
get size() {
return this.#head.length + this.#tail.length
}
constructor(iterable) {
this.#head = iterable !== undefined ? Array.from(iterable) : []
}
peek() {
if (this.size !== 0) {
const value = this.pop()
this.#tail.push(value)
return value
}
}
push(value) {
this.#head.push(value)
}
pop() {
let tail = this.#tail
if (tail.length === 0) {
const head = this.#head
if (head.length === 0) {
return
}
this.#head = tail
tail = this.#tail = head.reverse()
}
return tail.pop()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment