- 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:

推薦閱讀
- ClickHouse性能之巔:從架構設計解讀性能之謎
- Java程序設計實戰教程
- Amazon S3 Cookbook
- Visual Basic程序設計實驗指導(第4版)
- Spring Boot進階:原理、實戰與面試題分析
- Hands-On Automation Testing with Java for Beginners
- 從零開始學Linux編程
- C語言開發基礎教程(Dev-C++)(第2版)
- RESTful Java Web Services(Second Edition)
- Flowable流程引擎實戰
- ArcGIS for Desktop Cookbook
- 現代C:概念剖析和編程實踐
- Unity Android Game Development by Example Beginner's Guide
- 計算機組裝與維護(第二版)
- Raspberry Pi Blueprints