- Hands-On Data Structures and Algorithms with JavaScript
- Kashyap Mukkamala
- 162字
- 2021-06-30 19:12:12
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:

推薦閱讀
- Oracle從入門到精通(第3版)
- Java程序設計實戰教程
- Spring 5.0 By Example
- 大學計算機應用基礎實踐教程
- Vue.js 2 and Bootstrap 4 Web Development
- Securing WebLogic Server 12c
- 青少年Python編程入門
- 從零開始學Linux編程
- Solr Cookbook(Third Edition)
- Procedural Content Generation for C++ Game Development
- 并行編程方法與優化實踐
- C++ System Programming Cookbook
- Learning Shiny
- Game Development Patterns and Best Practices
- Mastering PostgreSQL 11(Second Edition)