| 998 | // key remains the best representative of that partition) and |
| 999 | // round-robins across buckets in insertion order. |
| 1000 | function _interleaveByKey(keyFn) { |
| 1001 | const buckets = new Map(); // key -> Upstream[] |
| 1002 | const order = []; // insertion order of distinct keys |
| 1003 | for (const u of this) { |
| 1004 | const k = keyFn(u) || ''; |
| 1005 | let b = buckets.get(k); |
| 1006 | if (!b) { b = []; buckets.set(k, b); order.push(k); } |
| 1007 | b.push(u); |
| 1008 | } |
| 1009 | const out = []; |
| 1010 | let pulled = true; |
| 1011 | while (pulled) { |
| 1012 | pulled = false; |
| 1013 | for (const k of order) { |
| 1014 | const b = buckets.get(k); |
| 1015 | if (b && b.length > 0) { |
| 1016 | out.push(b.shift()); |
| 1017 | pulled = true; |
| 1018 | } |
| 1019 | } |
| 1020 | } |
| 1021 | return out; |
| 1022 | } |
| 1023 | |
| 1024 | // ─── 4.9 Slicing & limits ─────────────────────────────────────────────── |
| 1025 | |