- Hands-On Data Structures and Algorithms with JavaScript
- Kashyap Mukkamala
- 162字
- 2025-02-25 19:09:24
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 = items.get(qKey);
return queue[queue.length - 1];
}
front() {
let queue = items.get(qKey);
return queue[0];
}
clear() {
items.set(qKey, []);
}
size() {
return items.get(qKey).length;
}
}
return Queue;
})();
We have again wrapped the entire class inside an IIFE because we don't want to make ;Queue items accessible from the outside:
