|
1 | 1 |
|
2 | | -export default class TinyQueue { |
3 | | - constructor(data = [], compare = (a, b) => (a < b ? -1 : a > b ? 1 : 0)) { |
4 | | - this.data = data; |
5 | | - this.length = this.data.length; |
6 | | - this.compare = compare; |
7 | | - |
8 | | - if (this.length > 0) { |
9 | | - for (let i = (this.length >> 1) - 1; i >= 0; i--) this._down(i); |
10 | | - } |
11 | | - } |
12 | | - |
13 | | - push(item) { |
14 | | - this.data.push(item); |
15 | | - this._up(this.length++); |
16 | | - } |
17 | | - |
18 | | - pop() { |
19 | | - if (this.length === 0) return undefined; |
20 | | - |
21 | | - const top = this.data[0]; |
22 | | - const bottom = this.data.pop(); |
23 | | - |
24 | | - if (--this.length > 0) { |
25 | | - this.data[0] = bottom; |
26 | | - this._down(0); |
27 | | - } |
28 | | - |
29 | | - return top; |
30 | | - } |
31 | | - |
32 | | - peek() { |
33 | | - return this.data[0]; |
34 | | - } |
35 | | - |
36 | | - _up(pos) { |
37 | | - const {data, compare} = this; |
38 | | - const item = data[pos]; |
39 | | - |
40 | | - while (pos > 0) { |
41 | | - const parent = (pos - 1) >> 1; |
42 | | - const current = data[parent]; |
43 | | - if (compare(item, current) >= 0) break; |
44 | | - data[pos] = current; |
45 | | - pos = parent; |
46 | | - } |
47 | | - |
48 | | - data[pos] = item; |
49 | | - } |
50 | | - |
51 | | - _down(pos) { |
52 | | - const {data, compare} = this; |
53 | | - const halfLength = this.length >> 1; |
54 | | - const item = data[pos]; |
55 | | - |
56 | | - while (pos < halfLength) { |
57 | | - let bestChild = (pos << 1) + 1; // initially it is the left child |
58 | | - const right = bestChild + 1; |
59 | | - |
60 | | - if (right < this.length && compare(data[right], data[bestChild]) < 0) { |
61 | | - bestChild = right; |
62 | | - } |
63 | | - if (compare(data[bestChild], item) >= 0) break; |
64 | | - |
65 | | - data[pos] = data[bestChild]; |
66 | | - pos = bestChild; |
67 | | - } |
68 | | - |
69 | | - data[pos] = item; |
70 | | - } |
71 | | -} |
| 2 | +export {default} from './index.cjs'; |
0 commit comments