File size: 968 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
40
41
42
43
44
45
46
47
48
49
export class Queue<T = any> {
  private existsMap: Map<T, boolean> = new Map()
  private firstItem: QueueItem<T> | null = null
  private lastItem: QueueItem<T> | null = null

  add(value: T) {
    if (!this.existsMap.has(value)) {
      this.existsMap.set(value, true)
      const item = {
        current: value,
        next: null,
      }
      if (!this.firstItem) {
        this.firstItem = item
      }
      if (this.lastItem) {
        this.lastItem.next = item
      }
      this.lastItem = item
    }
  }

  shift(): T | null {
    if (this.firstItem) {
      const item = this.firstItem
      this.firstItem = item.next
      if (!this.firstItem) {
        this.lastItem = null
      }
      this.existsMap.delete(item.current)
      return item.current
    }
    return null
  }

  isEmpty() {
    return !this.firstItem
  }

  has(value: T) {
    return this.existsMap.has(value)
  }
}

interface QueueItem<T> {
  current: T
  next: QueueItem<T> | null
}