Generalized array merging function with a custom comparator
TypeScript
Medium
generics
Task «Generalized array merging function with a custom comparator»
Implement a generic function `mergeArrays<T>` that takes two arrays of elements of type `T` and a comparator function `comparator: (a: T, b: T) => number`. The function should return a new array containing all elements from both arrays, sorted in ascending order according to the comparator. The original arrays must not be modified. If the comparator returns a negative number, `a` is considered smaller; a positive number — `b` is smaller; zero — equal. In case of equality, the order does not matter. Constraints: array lengths range from 1 to 10^5, elements can be of any type.
Input Format
The first line is the length of the first array N. The second line is N elements separated by spaces. The third line is the length of the second array M. The fourth line is M elements separated by spaces. The fifth line is a string with a comparator: 'number' for numbers (ascending comparison), 'string' for strings (lexicographic comparison).
Output Format
A string with the elements of the resulting array, separated by spaces.
Examples
Example 1
INPUT
5
3 1 4 1 5
OUTPUT
1 1 3 4 5
main.ts