1. 程式人生 > 程式設計 >使用js實現單鏈解決前端佇列問題的方法

使用js實現單鏈解決前端佇列問題的方法

使用場景

  • 比如前端需要處理什麼佇列一類的業務
  • 比如有人下單,需要彈出什麼彈窗

首先先宣告一個類

接收一個 陣列物件:items

class ChainQueue {
 constructor(items) {
  this.items = items || []
  this.maxNum = 200
 }
}

為佇列新增陣列佇列

// 新增陣列佇列
entryArrQueue(node) {
 Array.isArray(node)
 node.map(item => this.items.push(item))
}

為當前佇列新增單個物件

// 新增佇列
entryQueue(node) {
 if (this.items.length > this.maxNum) {
  return
 }
 if (Array.isArray(node)) {
  node.map(item => this.items.push(item))
 } else {
  this.items.push(node)
 }
}

刪除佇列,返回刪除的當前的專案

deleteQueue(func = () => {}) {
 assert(isFunc(func),`${func} is not function`)
 func(this.items.shift())
}

返回佇列的第一個

front() {
 return this.items[0]
}

清除佇列

clear() {
 this.items = []
}

所有程式碼

const isFunc = v => typeof v === 'function'
const assert = (condition,msg) => {
 if (!condition) throw new Error(`[dashboard]${msg}`)
}
class ChainQueue {
 constructor(items) {
  this.items = items || []
  this.maxNum = 200
 }

 // 新增陣列佇列
 entryArrQueue(node) {
  Array.isArray(node)
  node.map(item => this.items.push(item))
 }

 // 新增佇列
 entryQueue(node) {
  if (this.items.length > this.maxNum) {
   return
  }
  if (Array.isArray(node)) {
   node.map(item => this.items.push(item))
  } else {
   this.items.push(node)
  }
 }

 // 刪除佇列,返回刪除的當前的專案
 deleteQueue(func = () => {}) {
  assert(isFunc(func),`${func} is not function`)
  func(this.items.shift())
 }

 // 返回佇列的第一個
 front() {
  return this.items[0]
 }

 // 清除佇列
 clear() {
  this.items = []
 }
 get size() {
  return this.items.length
 }

 get isEmpty() {
  return !this.items.length
 }

 print() {
  console.log(this.items.toString())
  console.log(this.items)
 }
 result() {
  return this.items
 }
}

module.exports = ChainQueue

// export default ChainQueue
// export default (ChainQueue = new ChainQueue())

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。