I want to enhance this JS function by including types:
function zip(array1, array2) {
const length = Math.min(array1.length, array2.length);
const result = [];
for (let i = 0; i < length; i++) {
result.push([array1[i], array2[i]]);
}
return result;
}
const res = zip(["1","2","3"], [4,5,6])
The output of res looks like this:
[["1",4],["2",5],["3",6]]
Up to this point, I have come up with the following code snippet, but it has a flaw, as the result type does not differentiate between a string and a number, considering them both as possible types:
function zip<T,U>(array1: T[], array2: U[]): (T|U)[][] {
const length = Math.min(array1.length, array2.length);
const result = [];
for (let i = 0; i < length; i++) {
result.push([array1[i], array2[i]]);
}
return result;
}
const res = zip(["1","2","3"], [4,5,6])