系統城裝機大師 - 唯一官網:www.farandoo.com!

當前位置:首頁 > 網絡編程 > JavaScript > 詳細頁面

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

時間:2020-02-03來源:系統城作者:電腦系統城

使用場景

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

首先先聲明一個類

接收一個 數組對象:items


 
  1. class ChainQueue {
  2. constructor(items) {
  3. this.items = items || []
  4. this.maxNum = 200
  5. }
  6. }

為隊列添加數組隊列


 
  1. // 添加數組隊列
  2. entryArrQueue(node) {
  3. Array.isArray(node)
  4. node.map(item => this.items.push(item))
  5. }

為當前隊列添加單個對象


 
  1. // 添加隊列
  2. entryQueue(node) {
  3. if (this.items.length > this.maxNum) {
  4. return
  5. }
  6. if (Array.isArray(node)) {
  7. node.map(item => this.items.push(item))
  8. } else {
  9. this.items.push(node)
  10. }
  11. }

刪除隊列,返回刪除的當前的項目


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

返回隊列的第一個


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

清除隊列


 
  1. clear() {
  2. this.items = []
  3. }

所有代碼


 
  1. const isFunc = v => typeof v === 'function'
  2. const assert = (condition, msg) => {
  3. if (!condition) throw new Error(`[dashboard]${msg}`)
  4. }
  5. class ChainQueue {
  6. constructor(items) {
  7. this.items = items || []
  8. this.maxNum = 200
  9. }
  10.  
  11. // 添加數組隊列
  12. entryArrQueue(node) {
  13. Array.isArray(node)
  14. node.map(item => this.items.push(item))
  15. }
  16.  
  17. // 添加隊列
  18. entryQueue(node) {
  19. if (this.items.length > this.maxNum) {
  20. return
  21. }
  22. if (Array.isArray(node)) {
  23. node.map(item => this.items.push(item))
  24. } else {
  25. this.items.push(node)
  26. }
  27. }
  28.  
  29. // 刪除隊列,返回刪除的當前的項目
  30. deleteQueue(func = () => {}) {
  31. assert(isFunc(func), `${func} is not function`)
  32. func(this.items.shift())
  33. }
  34.  
  35. // 返回隊列的第一個
  36. front() {
  37. return this.items[0]
  38. }
  39.  
  40. // 清除隊列
  41. clear() {
  42. this.items = []
  43. }
  44. get size() {
  45. return this.items.length
  46. }
  47.  
  48. get isEmpty() {
  49. return !this.items.length
  50. }
  51.  
  52. print() {
  53. console.log(this.items.toString())
  54. console.log(this.items)
  55. }
  56. result() {
  57. return this.items
  58. }
  59. }
  60.  
  61. module.exports = ChainQueue
  62.  
  63. // export default ChainQueue
  64. // export default (ChainQueue = new ChainQueue())
  65.  

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

分享到:

相關信息

系統教程欄目

欄目熱門教程

人氣教程排行

站長推薦

熱門系統下載

jlzzjlzz亚洲乱熟在线播放