Last active
December 24, 2021 14:11
-
-
Save julien-f/d9394b1b0ab0623e5c4787f7852e7113 to your computer and use it in GitHub Desktop.
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
// 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