Here's a TypeScript implementation of a merge select function:
function mergeSelect<T, K extends keyof T>(
arrays: T[][],
selector: K,
compareFn?: (a: T[K], b: T[K]) => number
): T[] {
if (arrays.length === 0) return [];
if (arrays.length === 1) return [...arrays[0]];
// Default comparison function
const compare = compareFn || ((a, b) => {
if (a < b) return -1;
if (a > b) return 1;
return 0;
});
// Initialize pointers for each array
const pointers = new Array(arrays.length).fill(0);
const result: T[] = [];
while (true) {
let minIndex = -1;
let minValue: T[K] | undefined;
// Find the array with the smallest current element
for (let i = 0; i < arrays.length; i++) {
if (pointers[i] < arrays[i].length) {
const currentValue = arrays[i][pointers[i]][selector];
if (minIndex === -1 || compare(currentValue, minValue!) < 0) {
minIndex = i;
minValue = currentValue;
}
}
}
// If no valid element found, we're done
if (minIndex === -1) break;
// Add the smallest element to result and advance pointer
result.push(arrays[minIndex][pointers[minIndex]]);
pointers[minIndex]++;
}
return result;
}
// Example usage:
interface Person {
name: string;
age: number;
}
const array1: Person[] = [
{ name: "Alice", age: 25 },
{ name: "Charlie", age: 35 }
];
const array2: Person[] = [
{ name: "Bob", age: 30 },
{ name: "David", age: 40 }
];
const array3: Person[] = [
{ name: "Eve", age: 20 },
{ name: "Frank", age: 45 }
];
// Merge by age
const mergedByAge = mergeSelect([array1, array2, array3], 'age');
console.log(mergedByAge);
// Output: [Eve(20), Alice(25), Bob(30), Charlie(35), David(40), Frank(45)]
// Merge by name with custom comparator
const mergedByName = mergeSelect([array1, array2, array3], 'name',
(a, b) => a.localeCompare(b)
);
console.log(mergedByName);
This function takes multiple sorted arrays and merges them into a single sorted array based on a selected property. It uses a k-way merge algorithm with O(n log k) time complexity where n is the total number of elements and k is the number of arrays.