Home Web Front-end JS Tutorial Detailed introduction to queues in JavaScript (code examples)

Detailed introduction to queues in JavaScript (code examples)

Feb 13, 2019 am 09:36 AM
javascript data structure

This article brings you a detailed introduction (code example) about queues in JavaScript. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Definition of Queue

A queue is an ordered set of items that follows the first-in, first-out principle. The difference from a stack is that the stack does not matter whether it is pushed in or out. Stack operations are all performed on the top of the stack, while queues add elements to the end of the queue and remove elements from the top of the queue. A diagram is used to represent the process:

Detailed introduction to queues in JavaScript (code examples)

Use A more vivid example is: queuing service, the person who queues up first will always receive the service first, of course, regardless of the situation of queue jumping

Queue Creation

And Stack The creation is similar. First create a function representing the queue, and then define an array to save the elements in the queue:

function Queue() {
  let items = []
}
Copy after login

After creating the queue, you need to define some methods for it. Generally speaking, the queue contains the following methods:

  • enqueue(element): Add a new item to the end of the queue

  • dequeue(): Remove the first item of the queue and return Removed elements

  • front(): Returns the first item of the queue, and the queue does not make any changes

  • isEmpty(): If the queue There is no element in the return true, otherwise it returns false

  • size(): Returns the number of elements contained in the queue

Specific implementation:

function Queue() {
  let items = []
  // 向队列的尾部添加新元素
  this.enqueue = function (element) {
    items.push(element)
  }
  // 遵循先进先出原则,从队列的头部移除元素
  this.dequeue = function () {
    return items.shift()
  }
  // 返回队列最前面的项
  this.front = function () {
    return items[0]
  }
  // 返回队列是否为空
  this.isEmpty = function () {
    return items.length === 0
  }
  // 返回队列的长度
  this.size = function () {
    return items.length
  }
  // 打印队列,方便观察
  this.print = function () {
    console.log(items.toString())
  }
}
Copy after login

Use of queue

Next let’s look at the use of queue:

let queue = new Queue()
queue.enqueue('a')
queue.enqueue('b')
queue.enqueue('c')
queue.dequeue()
queue.print()
Copy after login

First add three elements to the queue: a, b, c, then remove an element from the queue, and finally print the existing queue. Let us illustrate this process together:

Detailed introduction to queues in JavaScript (code examples)

es6 implements Queue

Same as implementing the Stack class, you can also use the es6 class syntax to implement the Queue class, use WeakMap to save private attribute items, and use closures to return the Queue class. Let’s look at the specific implementation:

let Queue = (function () {
  let items = new WeakMap
  class Queue {
    constructor () {
      items.set(this, [])
    }
    enqueue (element) {
      let q = items.get(this)
      q.push(element)
    }
    dequeue () {
      let q = items.get(this)
      return q.shift()
    }
    front () {
      let q = items.get(this)
      return q[0]
    }
    isEmpty () {
      let q = items.get(this)
      return q.length === 0
    }
    size () {
      let q = items.get(this)
      return q.length
    }
    print () {
      let q = items.get(this)
      console.log(q.toString())
    }
  }
  return Queue
})()
let queue = new Queue()
queue.enqueue('a')
queue.enqueue('b')
queue.enqueue('c')
queue.dequeue()
queue.print()
Copy after login

Priority Queue

Priority queue, as its name implies: each element in the queue will have its own priority. When inserting, the insertion operation will be performed according to the order of priority, which is a bit different from the previous queue implementation. The difference is that there are more elements in the queue with priority attributes. Let’s look at the specific code:

function PriorityQueue() {
  let items = []
  // 队列元素,多定义一个优先级变量
  function QueueElement(element, priority) {
    this.element = element
    this.priority = priority
  }
  this.enqueue = function (element, priority) {
    let queueElement = new QueueElement(element, priority)
    let added = false
    for (let i = 0; i <p> When joining the queue, if the queue is empty, add it directly to the queue. Otherwise, compare, and the smaller priority will be given priority. The higher the level, the higher the priority is placed at the front of the queue. Let’s use a diagram to see the calling process: <br></p><p><img src="/static/imghw/default1.png" data-src="https://img.php.cn/upload/image/471/355/539/1550021327400018.png" class="lazy" title="1550021327400018.png" alt="Detailed introduction to queues in JavaScript (code examples)"></p><p   style="max-width:90%"><strong>Circular Queue</strong></p><p> As the name suggests, the circular queue is: given a number, then iterates the queue, removes an item from the beginning of the queue, and then adds it to the end of the queue. When the loop reaches the given number, jump out of the loop and move from the head of the queue. Remove one item until there is one element left. Let’s look at the specific code: </p><pre class="brush:php;toolbar:false">unction Queue() {
  let items = []
  this.enqueue = function (element) {
    items.push(element)
  }
  this.dequeue = function () {
    return items.shift()
  }
  this.front = function () {
    return items[0]
  }
  this.isEmpty = function () {
    return items.length === 0
  }
  this.size = function () {
    return items.length
  }
  this.print = function () {
    console.log(items.toString())
  }
}
function loopQueue(list, num) {
  let queue = new Queue()
  for (let i = 0; i<list.length> 1) {
    for (let j = 0; j<num console.log></num></list.length>
Copy after login

The above is the detailed content of Detailed introduction to queues in JavaScript (code examples). For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Compare complex data structures using Java function comparison Compare complex data structures using Java function comparison Apr 19, 2024 pm 10:24 PM

When using complex data structures in Java, Comparator is used to provide a flexible comparison mechanism. Specific steps include: defining the comparator class, rewriting the compare method to define the comparison logic. Create a comparator instance. Use the Collections.sort method, passing in the collection and comparator instances.

In-depth understanding of reference types in Go language In-depth understanding of reference types in Go language Feb 21, 2024 pm 11:36 PM

Reference types are a special data type in the Go language. Their values ​​do not directly store the data itself, but the address of the stored data. In the Go language, reference types include slices, maps, channels, and pointers. A deep understanding of reference types is crucial to understanding the memory management and data transfer methods of the Go language. This article will combine specific code examples to introduce the characteristics and usage of reference types in Go language. 1. Slices Slices are one of the most commonly used reference types in the Go language.

Java data structures and algorithms: in-depth explanation Java data structures and algorithms: in-depth explanation May 08, 2024 pm 10:12 PM

Data structures and algorithms are the basis of Java development. This article deeply explores the key data structures (such as arrays, linked lists, trees, etc.) and algorithms (such as sorting, search, graph algorithms, etc.) in Java. These structures are illustrated through practical examples, including using arrays to store scores, linked lists to manage shopping lists, stacks to implement recursion, queues to synchronize threads, and trees and hash tables for fast search and authentication. Understanding these concepts allows you to write efficient and maintainable Java code.

Full analysis of Java collection framework: dissecting data structure and revealing the secret of efficient storage Full analysis of Java collection framework: dissecting data structure and revealing the secret of efficient storage Feb 23, 2024 am 10:49 AM

Overview of Java Collection Framework The Java collection framework is an important part of the Java programming language. It provides a series of container class libraries that can store and manage data. These container class libraries have different data structures to meet the data storage and processing needs in different scenarios. The advantage of the collection framework is that it provides a unified interface, allowing developers to operate different container class libraries in the same way, thereby reducing the difficulty of development. Data structures of the Java collection framework The Java collection framework contains a variety of data structures, each of which has its own unique characteristics and applicable scenarios. The following are several common Java collection framework data structures: 1. List: List is an ordered collection that allows elements to be repeated. Li

PHP data structure: The balance of AVL trees, maintaining an efficient and orderly data structure PHP data structure: The balance of AVL trees, maintaining an efficient and orderly data structure Jun 03, 2024 am 09:58 AM

AVL tree is a balanced binary search tree that ensures fast and efficient data operations. To achieve balance, it performs left- and right-turn operations, adjusting subtrees that violate balance. AVL trees utilize height balancing to ensure that the height of the tree is always small relative to the number of nodes, thereby achieving logarithmic time complexity (O(logn)) search operations and maintaining the efficiency of the data structure even on large data sets.

Learn the secrets of Go language data structures in depth Learn the secrets of Go language data structures in depth Mar 29, 2024 pm 12:42 PM

In-depth study of the mysteries of Go language data structure requires specific code examples. As a concise and efficient programming language, Go language also shows its unique charm in processing data structures. Data structure is a basic concept in computer science, which aims to organize and manage data so that it can be accessed and manipulated more efficiently. By in-depth learning the mysteries of Go language data structure, we can better understand how data is stored and operated, thereby improving programming efficiency and code quality. 1. Array Array is one of the simplest data structures

PHP SPL data structures: Inject speed and flexibility into your projects PHP SPL data structures: Inject speed and flexibility into your projects Feb 19, 2024 pm 11:00 PM

Overview of the PHPSPL Data Structure Library The PHPSPL (Standard PHP Library) data structure library contains a set of classes and interfaces for storing and manipulating various data structures. These data structures include arrays, linked lists, stacks, queues, and sets, each of which provides a specific set of methods and properties for manipulating data. Arrays In PHP, an array is an ordered collection that stores a sequence of elements. The SPL array class provides enhanced functions for native PHP arrays, including sorting, filtering, and mapping. Here is an example of using the SPL array class: useSplArrayObject;$array=newArrayObject(["foo","bar","baz"]);$array

Python performance optimization practice: from basics to advanced Python performance optimization practice: from basics to advanced Feb 20, 2024 pm 12:00 PM

Basic Optimizations Use the correct Python version: Newer versions of python are generally more performant, offer better memory management and built-in optimizations. Choose the right library: You can save time and improve performance by using purpose-built libraries instead of writing code from scratch. Reduce the number of loops: If possible, avoid using nested loops. Using list comprehensions and generator expressions are more efficient alternatives. Data structure optimization chooses the right container: lists are good for random access, dictionaries are good for fast key-value lookups, and tuples are good for immutable data. Use preallocated memory: By preallocating the size of an array or list, you can reduce the overhead of memory allocation and defragmentation. Leveraging Numpy and Pandas: For scientific computing and data analysis, Num

See all articles