Skip to content

Commit 9a7f19c

Browse files
authored
Create merge.ts
1 parent 55c2844 commit 9a7f19c

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

src/merge.ts

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
import min from './min';
2+
import type {compareFn, mapFn} from './_types';
3+
4+
/**
5+
* Merges values from sorted iterables.
6+
* @param xs iterables
7+
* @param fc compare function (a, b)
8+
* @param fm map function (v, i, x)
9+
*/
10+
function merge<T, U=T>(xs: T[][], fc: compareFn<T|U>=null, fm: mapFn<T, T|U>=null): T[] {
11+
var X = xs.length, a = [];
12+
if(X===0) return a;
13+
var is = new Array(X).fill(0);
14+
var xs = xs.filter(x => x.length>0);
15+
while(xs.length>0) {
16+
for(var i=0, I=xs.length, vs=[]; i<I; i++)
17+
vs[i] = xs[i][is[i]];
18+
var i = min(vs, fc, fm)[0];
19+
a.push(vs[i]);
20+
if(++is[i]<xs[i].length) continue;
21+
xs.splice(i, 1);
22+
is.splice(i, 1);
23+
}
24+
return a;
25+
}
26+
export default merge;

0 commit comments

Comments
 (0)