File size: 724 Bytes
4d70170
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import throttle from 'lodash/throttle'

interface ThrottleQueueItem {
  fn: Function
  key: string
}

export function createThrottleQueue(wait: number) {
  const queue: ThrottleQueueItem[] = []
  const tracker: Map<string, ThrottleQueueItem> = new Map()

  function flush() {
    for (const item of queue) {
      item.fn()
      tracker.delete(item.key)
    }
    queue.length = 0
  }

  const throttledFlush = throttle(flush, wait)

  function add(key: string, fn: Function) {
    if (!tracker.has(key)) {
      const item = { key, fn }
      queue.push(item)
      tracker.set(key, item)
      throttledFlush()
    }
    else {
      const item = tracker.get(key)!
      item.fn = fn
    }
  }

  return {
    add,
  }
}