Creating a queue
Of the four types of the queue that we have discussed earlier, first, we will implement a simple queue and then move on to modify it for each type of the subsequent queue.
A simple queue
Similar to a stack, we will create a queue using the following steps:
- Define a
constructor()
:
class Queue { constructor() { } }
- We will be using
WeakMap()
for in-memory data storage just like we did for stacks:
const qKey = {}; const items = new WeakMap(); class Queue { constructor() { } }
- Implement the methods described previously in the API:
var Queue = (() => { const qKey = {}; const items = new WeakMap(); class Queue { constructor() { items.set(qKey, []); } add(element) { let queue = items.get(qKey); queue.push(element); } remove() { let queue = items.get(qKey); return queue.shift(); } peek() { let queue...