| 10 | } |
| 11 | |
| 12 | export class Queue<T> implements IQueue { |
| 13 | protected items: T[] = []; |
| 14 | private _capacity?: number; |
| 15 | |
| 16 | constructor(capacity?: number) { |
| 17 | this._capacity = capacity; |
| 18 | } |
| 19 | |
| 20 | get size(): number { |
| 21 | return this.items.length; |
| 22 | } |
| 23 | |
| 24 | get capacity(): number | undefined { |
| 25 | return this._capacity; |
| 26 | } |
| 27 | |
| 28 | get freeSpace(): number | undefined { |
| 29 | if (!this._capacity) return undefined; |
| 30 | |
| 31 | return this._capacity - this.size; |
| 32 | } |
| 33 | |
| 34 | put(item: T): void { |
| 35 | this.putMany([item]); |
| 36 | } |
| 37 | |
| 38 | putMany(items: T[]): void { |
| 39 | if (this.freeSpace && items.length > this.freeSpace) { |
| 40 | throw new Error('Queue exceeds max size'); |
| 41 | } |
| 42 | this.items.push(...items); |
| 43 | } |
| 44 | |
| 45 | peek(): T | undefined { |
| 46 | return this.items[0]; |
| 47 | } |
| 48 | |
| 49 | take(): T | undefined { |
| 50 | return this.items.shift(); |
| 51 | } |
| 52 | |
| 53 | takeMany(size: number): T[] { |
| 54 | const sizeCapped = Math.min(this.size, size); |
| 55 | |
| 56 | const result = this.items.slice(0, sizeCapped); |
| 57 | this.items = this.items.slice(sizeCapped); |
| 58 | |
| 59 | return result; |
| 60 | } |
| 61 | |
| 62 | takeAll(): T[] { |
| 63 | const result = this.items; |
| 64 | |
| 65 | this.items = []; |
| 66 | return result; |
| 67 | } |
| 68 | |
| 69 | flush(): void { |
nothing calls this directly
no outgoing calls
no test coverage detected