Skip to content

Instantly share code, notes, and snippets.

@nfroidure
Last active December 31, 2018 16:43
Show Gist options
  • Save nfroidure/5472480 to your computer and use it in GitHub Desktop.
Save nfroidure/5472480 to your computer and use it in GitHub Desktop.
A simple Javascript Queue based on an Array wrap and using setters/getters. More explanations here : https://insertafter.com/blog-fifo_lifo_javascript.html
class Queue {
constructor(...elements) {
// Initializing the queue with given arguments
this.elements = [...elements];
}
// Proxying the push/shift methods
push(...args) {
return this.elements.push(...args);
}
shift(...args) {
return this.elements.shift(...args);
}
// Add some length utility methods
get length() {
return this.elements.length;
}
set length(length) {
return this.elements.length = length;
}
}
// Usage
const q = new Queue(0,1);
q.push(2);
console.log(q.length); // 3
while(q.length)
console.log(q.shift()); // 0, 1, 2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment