current position:Home>JavaScript queue“

JavaScript queue“

2022-04-29 09:42:08Aaron Con

Stack is a first in first out data structure , But for us Javascript There is no such structure in language , But we can use the array push and shift Operation to achieve

1. Implement queue structure

const queue = []
queue.push (2)
const item1 = queue.shift()
const item2 = queue.shift() 

2. Application scenarios

  • Line up to do nucleic acid

Go first and finish first

  • JS Task queues in asynchrony

JS It's single threaded , Unable to handle asynchronous concurrent tasks
Use task queues to process asynchronous tasks

3. practice

Number of recent requests

Write a RecentCounter Class to calculate the most recent request in a specific time range . Please implement RecentCounter class :
RecentCounter() Initialize counter , The number of requests is 0 .
int ping(int t) In time t Add a new request , among t Represents a time in milliseconds , And go back to the past 3000 The number of all requests in milliseconds ( Including new requests ). To be precise , Back in the [t-3000, t] The number of requests that occurred in .
Guarantee Every time the ping All calls to the t value .

var RecentCounter = function() {
    this.q = []

/** * @param {number} t * @return {number} */ = function(t) {
    while(this.q[0] < t - 3000) {
    return this.q.length

copyright notice
author[Aaron Con],Please bring the original link to reprint, thank you.

Random recommended