I am currently working on developing a function that can merge and sort pre-sorted arrays into one single sorted array. This function takes an array of arrays containing objects, along with a specified key for comparison purposes. It is important to ensure that the value corresponding to the provided key is always numeric.
Here's the progress I have made so far:
const sortMerge = <
A extends Array<I>,
K extends keyof A[number],
I = A[number] & {
[key in K]: number;
},
>(
arrays: A[],
key: K,
sortMethod = SortMethod.asc,
) => {
const indexesOfArrays = arrays.map(() => 0);
const mergedSorted = [];
while (arrays.some((array, i) => array.length > indexesOfArrays[i])) {
const currentItemsOfArrays = arrays.map(
(array, arrayIndex) => array[indexesOfArrays[arrayIndex]],
);
const comparison = currentItemsOfArrays.map((item) =>
item ? item[key] : (sortMethod === SortMethod.asc ? Infinity : -Infinity),
);
const nextArrayIndex = comparison.indexOf(
Math[sortMethod === SortMethod.asc ? 'min' : 'max'](...comparison),
);
const nextItem = currentItemsOfArrays[nextArrayIndex];
mergedSorted.push(nextItem);
indexesOfArrays[nextArrayIndex]++;
}
return mergedSorted;
};
While everything seems to be working fine, there is an issue with recognizing I[K]
as a numeric type, even though I attempted to define both K
and I
as generics.
Could you please point out what I may be doing incorrectly?
Anticipated errors/types:
const missingKey = [ { a: 1 } ];
const valid = [ { a: 2, b: 3 } ];
const anotherValid = [ { c: 3, b: 4 } ];
sortMerge([missingKey, valid], 'b') // missingKey[number] is missing property 'b';
sortMerge([valid, anotherValid], 'b') // expected return type: ({ a: number, b: number } | { c: number, b: number })[]