Last active
December 31, 2018 16:43
-
-
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
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
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