-
Notifications
You must be signed in to change notification settings - Fork 0
/
mergeAscends.ts
192 lines (180 loc) · 6.87 KB
/
mergeAscends.ts
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
import DIE from "phpdie";
import { sortBy, type Ord } from "rambda";
import { toStream } from "./froms";
import { sflow, type FlowSource } from "./index";
interface MergeBy {
<T>(ordFn: (input: T) => Ord, srcs: FlowSource<FlowSource<T>>): sflow<T>;
<T>(ordFn: (input: T) => Ord): {
(srcs: FlowSource<FlowSource<T>>): sflow<T>;
};
}
/**
* merge multiple stream by ascend order, assume all input stream is sorted by ascend
* output stream will be sorted by ascend too.
*
* if one of input stream is not sorted by ascend, it will throw an error.
*
* @param ordFn a function to get the order of input
* @param srcs a list of input stream
* @returns a new stream that merge all input stream by ascend order
* @deprecated use {@link mergeStreamsByAscend}
*/
export const mergeAscends: MergeBy = <T>(
ordFn: (input: T) => Ord,
_srcs?: FlowSource<FlowSource<T>>,
) => {
if (!_srcs) return ((srcs: any) => mergeAscends(ordFn, srcs)) as any;
return sflow(
new ReadableStream<T>(
{
pull: async (ctrl) => {
const srcs = await sflow(_srcs).toArray();
const slots = srcs.map(() => undefined as { value: T } | undefined);
const pendingSlotRemoval = srcs.map(
() => undefined as PromiseWithResolvers<void> | undefined,
);
const drains = srcs.map(() => false);
let lastMinValue: T | undefined = undefined;
await Promise.all(
srcs.map(async (src, i) => {
for await (const value of sflow(src)) {
while (slots[i] !== undefined) {
if (shiftMinValueIfFull()) continue;
pendingSlotRemoval[i] = Promise.withResolvers<void>();
await pendingSlotRemoval[i]!.promise; // wait for this slot empty;
}
slots[i] = { value };
shiftMinValueIfFull();
}
// done
drains[i] = true;
pendingSlotRemoval.map((e) => e?.resolve());
await Promise.all(pendingSlotRemoval.map((e) => e?.promise));
const allDrain = drains.every(Boolean);
if (allDrain) {
while (slots.some((e) => e !== undefined))
shiftMinValueIfFull();
ctrl.close();
}
function shiftMinValueIfFull() {
const isFull = slots.every(
(slot, i) => slot !== undefined || drains[i],
);
if (!isFull) return false;
const fullSlots = slots
.flatMap((e) => (e !== undefined ? [e] : []))
.map((e) => e.value);
const minValue = sortBy(ordFn, fullSlots)[0];
const minIndex = slots.findIndex((e) => e?.value === minValue);
if (lastMinValue !== undefined) {
const ordered = sortBy(ordFn, [lastMinValue, minValue]);
(ordered[0] === lastMinValue && ordered[1] === minValue) ||
DIE(`
MergeAscendError: one of source stream is not ascending ordered.
stream index: ${minIndex}
prev: ${ordFn(lastMinValue)}
prev: ${JSON.stringify(lastMinValue)}
curr: ${ordFn(minValue)}
curr: ${JSON.stringify(minValue)}
`);
}
lastMinValue = minValue;
ctrl.enqueue(minValue);
slots[minIndex] = undefined;
pendingSlotRemoval[minIndex]?.resolve();
pendingSlotRemoval[minIndex] = undefined;
return true;
}
}),
);
},
},
{ highWaterMark: 0 },
),
);
};
/**
* merge multiple stream by ascend order, assume all input stream is sorted by ascend
* output stream will be sorted by ascend too.
*
* if one of input stream is not sorted by ascend, it will throw an error.
*
* @param ordFn a function to get the order of input
* @param srcs a list of input stream
* @returns a new stream that merge all input stream by ascend order
* @deprecated use {@link mergeStreamsByAscend}
*/
export const mergeDescends: MergeBy = <T>(
ordFn: (input: T) => Ord,
_srcs?: FlowSource<FlowSource<T>>,
) => {
if (!_srcs) return ((srcs: any) => mergeDescends(ordFn, srcs)) as any;
return toStream(
new ReadableStream<T>(
{
pull: async (ctrl) => {
const srcs = await sflow(_srcs).toArray();
const slots = srcs.map(() => undefined as { value: T } | undefined);
const pendingSlotRemoval = srcs.map(
() => undefined as PromiseWithResolvers<void> | undefined,
);
const drains = srcs.map(() => false);
let lastMaxValue: T | undefined = undefined;
await Promise.all(
srcs.map(async (src, i) => {
for await (const value of toStream(src)) {
while (slots[i] !== undefined) {
if (shiftMaxValueIfFull()) continue;
pendingSlotRemoval[i] = Promise.withResolvers<void>();
await pendingSlotRemoval[i]!.promise; // wait for this slot empty;
}
slots[i] = { value };
shiftMaxValueIfFull();
}
// done
drains[i] = true;
pendingSlotRemoval.map((e) => e?.resolve());
await Promise.all(pendingSlotRemoval.map((e) => e?.promise));
const allDrain = drains.every(Boolean);
if (allDrain) {
while (slots.some((e) => e !== undefined))
shiftMaxValueIfFull();
ctrl.close();
}
function shiftMaxValueIfFull() {
const isFull = slots.every(
(slot, i) => slot !== undefined || drains[i],
);
if (!isFull) return false;
const fullSlots = slots
.flatMap((e) => (e !== undefined ? [e] : []))
.map((e) => e.value);
const maxValue = sortBy(ordFn, fullSlots).toReversed()[0];
const maxIndex = slots.findIndex((e) => e?.value === maxValue);
if (lastMaxValue !== undefined) {
const ordered = sortBy(ordFn, [maxValue, lastMaxValue]);
(ordered[0] === maxValue && ordered[1] === lastMaxValue) ||
DIE(`
MergeDescendError: one of source stream is not descending ordered.
stream index: ${maxIndex}
prev: ${ordFn(lastMaxValue)}
prev: ${JSON.stringify(lastMaxValue)}
curr: ${ordFn(maxValue)}
curr: ${JSON.stringify(maxValue)}
`);
}
lastMaxValue = maxValue;
ctrl.enqueue(maxValue);
slots[maxIndex] = undefined;
pendingSlotRemoval[maxIndex]?.resolve();
pendingSlotRemoval[maxIndex] = undefined;
return true;
}
}),
);
},
},
{ highWaterMark: 0 },
),
);
};