惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

C
Check Point Blog
AI
AI
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
U
Unit 42
Vercel News
Vercel News
Stack Overflow Blog
Stack Overflow Blog
P
Proofpoint News Feed
Microsoft Security Blog
Microsoft Security Blog
The GitHub Blog
The GitHub Blog
WordPress大学
WordPress大学
Martin Fowler
Martin Fowler
博客园 - 【当耐特】
B
Blog
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
Apple Machine Learning Research
Apple Machine Learning Research
博客园_首页
F
Full Disclosure
Google DeepMind News
Google DeepMind News
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
H
Help Net Security
Recorded Future
Recorded Future
N
News and Events Feed by Topic
雷峰网
雷峰网
V
Vulnerabilities – Threatpost
Schneier on Security
Schneier on Security
aimingoo的专栏
aimingoo的专栏
S
Schneier on Security
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
O
OpenAI News
Project Zero
Project Zero
罗磊的独立博客
G
GRAHAM CLULEY
腾讯CDC
P
Privacy International News Feed
V
V2EX
Application and Cybersecurity Blog
Application and Cybersecurity Blog
Hugging Face - Blog
Hugging Face - Blog
爱范儿
爱范儿
H
Heimdal Security Blog
L
LINUX DO - 热门话题
Forbes - Security
Forbes - Security
美团技术团队
MongoDB | Blog
MongoDB | Blog
Security Latest
Security Latest
M
MIT News - Artificial intelligence
T
Tor Project blog
Cisco Talos Blog
Cisco Talos Blog
宝玉的分享
宝玉的分享
T
Threat Research - Cisco Blogs
TaoSecurity Blog
TaoSecurity Blog

Dmitri Pavlutin Blog

Pure Functions in JavaScript: A Beginner's Guide Record Type in TypeScript: A Quick Intro How to Write Comments in React: The Good, the Bad and the Ugly 4 Ways to Create an Enum in JavaScript React forwardRef(): How to Pass Refs to Child Components TypeScript Function Types: A Beginner's Guide How to Use v-model to Access Input Values in Vue Mastering Vue refs: From Zero to Hero Environment Variables in JavaScript: process.env 5 Must-Know Differences Between ref() and reactive() in Vue How to Destructure Props in Vue (Composition API) Triangulation in Test-Driven Development How to Use nextTick() in Vue Programming to Interface Vs to Implementation A Smarter JavaScript Mapper: array.flatMap() Array Grouping in JavaScript: Object.groupBy() How to Access ES Module Metadata using import.meta JSON Modules in JavaScript How to Trim Strings in JavaScript TypeScript Function Overloading How to Debounce and Throttle Callbacks in Vue How to Show/Hide Elements in Vue Sparse vs Dense Arrays in JavaScript How to Fill an Array with Initial Values in JavaScript Covariance and Contravariance in TypeScript What are Higher-Order Functions in JavaScript? How to Use TypeScript with React Components Index Signatures in TypeScript How to Use React useReducer() Hook unknown vs any in TypeScript A Guide to React Context and useContext() Hook How to Use Promise.any() 2 Ways to Remove a Property from an Object in JavaScript 'return await promise' vs 'return promise' in JavaScript How to Use Promise.allSettled() How to Use fetch() with JSON JavaScript Promises: then(f,f) vs then(f).catch(f) What is a Promise in JavaScript? How to Use Promise.all() A Simple Guide to Component Props in React Don't Stop Me Now: How to Use React useTransition() hook A Simple Explanation of JavaScript Variables: const, let, var ES Modules Dynamic Import How to Memoize with React.useMemo() How to Cleanup Async Effects in React Why Math.max() Without Arguments Returns -Infinity How to Debounce and Throttle Callbacks in React Don't Confuse Function Expressions and Function Declarations in JavaScript How to Use ES Modules in Node.js Solving a Mystery Behavior of parseInt() in JavaScript How to Use Array Reduce Method in JavaScript 3 Ways to Merge Arrays in JavaScript A Guide to Jotai: the Minimalist React State Management Library The Difference Between Values and References in JavaScript A Helpful Algorithm to Determine "this" value in JavaScript React useRef() Hook Explained in 3 Steps 7 Interview Questions on "this" keyword in JavaScript. Can You Answer Them? How to Greatly Enhance fetch() with the Decorator Pattern 7 Interview Questions on JavaScript Closures. Can You Answer Them? What's a Method in JavaScript? array.sort() Does Not Simply Sort Numbers in JavaScript How to Solve the Infinite Loop of React.useEffect() The New Array Method You'll Enjoy: array.at(index) What's the Difference between DOM Node and Element? Why Promises Are Faster Than setTimeout()? Everything About Callback Functions in JavaScript How React Updates State 5 Mistakes to Avoid When Using React Hooks 5 Best Practices to Write Quality JavaScript Variables Type checking in JavaScript: typeof and instanceof operators 3 Ways to Check if a Variable is Defined in JavaScript React Forms Tutorial: Access Input Values, Validate, Submit Forms Prototypal Inheritance in JavaScript How to Timeout a fetch() Request How to Learn JavaScript If You're a Beginner A Simple Explanation of React.useEffect() A Simple Explanation of JavaScript Iterators How to Use React Controlled Inputs Everything about null in JavaScript How to Use Fetch with async/await Getting Started with Arrow Functions in JavaScript An Interesting Explanation of async/await in JavaScript Front-end Architecture: Stable and Volatile Dependencies Is it Safe to Compare JavaScript Strings? How to Access Object's Keys, Values, and Entries in JavaScript What Actually is a String in JavaScript? 3 Ways to Shallow Clone Objects in JavaScript (w/ bonuses) Checking if an Array Contains a Value in JavaScript JavaScript Event Delegation: A Beginner's Guide How to Parse URL in JavaScript: hostname, pathname, query, hash 3 Ways to Detect an Array in JavaScript How to Get the Screen, Window, and Web Page Sizes in JavaScript 3 Ways to Check If an Object Has a Property/Key in JavaScript How to Compare Objects in JavaScript Object.is() vs Strict Equality Operator in JavaScript Own and Inherited Properties in JavaScript 5 Differences Between Arrow and Regular Functions How to Use Object Destructuring in JavaScript Your Guide to React.useCallback() 5 JavaScript Scope Gotchas
How to Implement a Queue in JavaScript
Dmitri Pavlutin · 2021-03-16 · via Dmitri Pavlutin Blog

Being a good developer requires knowledge from multiple disciplines.

The first requirement is to know the programming language of your choice. If you're reading this post, most likely you use JavaScript.

However, on top of knowing the programming language, you also have to understand how to organize data to easily and effectively manipulate data depending on the task. That's where the data structures come into play.

In this post, I'm going to describe the queue data structure, what operations it has, as well as present you with a queue implementation in JavaScript.

1. The queue data structure

If you enjoy traveling (like I do), most likely you passed the check-in process at the airport. If there are a lot of travelers willing to check-in, naturally a queue of people is formed at the check-in desk.

Airport Check-In Queue

A traveler who's just entered the airport and wants to check-in is going to enqueue into the queue. Another traveler that has just passed the check-in process at the desk is dequeued from the queue.

This is the real-world example of a queue — and the queue data structure works the same way.

The queue is a type of First Input-First Output (FIFO) data structure. The first enqueued item (input) is the first to dequeue (output).

A queue has 2 pointers: head and tail. The earliest enqueued item in the queue is at the head, while the latest enqueued item is at the tail of the queue.

Recalling the airport example, the traveler at the check-in desk is the head of the queue. The traveler who has just entered the queue is at the tail.

Queue Data Structure

From a higher-point of view, the queue is the data structure that lets you process items, one at a time, in the same order they come in.

2. The operations on queues

The queue supports 2 main operations: enqueue and dequeue. Additionally, you might find it useful to have the peek and length operations.

2.1 Enqueue operation

The enqueue operation inserts an item at the tail of the queue. The enqueued item becomes the tail of the queue.

Queue: Enqueue Operation

The enqueue operation in the picture above inserts the item 8 at the tail. 8 becomes the tail of the queue.

2.2 Dequeue operation

The dequeue operation extracts the item at the head of the queue. The next item in the queue becomes the head.

Queue Data Structure: Dequeue Operation

In the picture above the dequeue operation returns and removes the item 7 from the queue. After dequeue, item 2 becomes the new head.

2.3 Peek operation

The peek operation reads the head of the queue, without altering the queue.

Queue Data Structure: Peek Operation

Item 7 is the head of the queue in the picture above. The peek operation simply returns the head — the item 7 — without modifying the queue.

2.4 Queue length

Length operation counts how many items the queue contains.

Queue Data Structure: Length

The queue in the picture has 4 items: 4, 6, 2, and 7. As result, the queue length is 4.

2.5 Queue operations time complexity

What's important regarding all of the queue operations — enqueue, dequeue, peek and length — all these operations must be performed in constant time O(1).

The constant time O(1) means that no matter the size of the queue (it can have 10 or 1 million items): the enqueue, dequeue, peek and length operations must be performed at relatively the same time.

3. Implementing a queue in JavaScript

Let's look at a possible implementation of the queue data structure while maintaining the requirement that all operations must perform in constant time O(1).


class Queue {

constructor() {

this.items = {};

this.headIndex = 0;

this.tailIndex = 0;

}

enqueue(item) {

this.items[this.tailIndex] = item;

this.tailIndex++;

}

dequeue() {

const item = this.items[this.headIndex];

delete this.items[this.headIndex];

this.headIndex++;

return item;

}

peek() {

return this.items[this.headIndex];

}

get length() {

return this.tailIndex - this.headIndex;

}

}

const queue = new Queue();

queue.enqueue(7);

queue.enqueue(2);

queue.enqueue(6);

queue.enqueue(4);

queue.dequeue(); // => 7

queue.peek(); // => 2

queue.length; // => 3


Open the demo.

const queue = new Queue() is how you create an instance of a queue.

Calling queue.enqueue(7) method enqueues the item 7 into the queue.

queue.dequeue() dequeues a head item from the queue, while queue.peek() just peeks the item at the head.

Finally, queue.length shows how many items are still in the queue.

Regarding the implementation: inside the Queue class the plain object this.items keeps the items of the queue by a numerical index. The index of the head item is tracked by this.headIndex, and the tail item is tracked by this.tailIndex.

Queue methods complexity

queue(), dequeue(), peek() and length() methods of the Queue class use only:

  • Property accessors (e.g. this.items[this.headIndex]),
  • Or perform aritmetical operations (e.g. this.headIndex++)

Thus the time complexity of these methods is constant time O(1).

4. Further improvements

The above queue implementation is very simple to demonstrate the underlying algorithm to keep the queue operations at O(1) complexity.

But you can easily make further improvements.

For example, if you want to protect yourself from dequeuing or picking the head of an empty queue, then you can add the verification for emptiness:


class Queue {

constructor() {

this.items = {};

this.headIndex = 0;

this.tailIndex = 0;

}

enqueue(item) {

this.items[this.tailIndex] = item;

this.tailIndex++;

}

dequeue() {

this.#validate() // validate if not empty

const item = this.items[this.headIndex];

delete this.items[this.headIndex];

this.headIndex++;

return item;

}

peek() {

this.#validate() // validate if not empty

return this.items[this.headIndex];

}

#validate() { // validation logic

if (this.headIndex === this.tailIndex) {

throw new Error('Cannot perform operation on an empty queue')

}

}

get length() {

return this.tailIndex - this.headIndex;

}

}

const queue = new Queue();

queue.dequeue(); // throws error


Open the demo.

If you call, for example, queue.dequeue() on an empty queue, the method throws an error.

5. Summary

The queue data structure is a type of First Input First Output (FIFO): the earliest enqueued item is the earlies to dequeue.

The queue has 2 main operations: enqueue and dequeue. Additionally, queues can have helper operations like peek and length.

All queue operations have to be performed in constant time O(1).