Implement Zip for Arrays in JavaScript
Imagine you have multiple lists of data, and you want to combine them element by element into a new structure. The "zip" operation is a fundamental concept in functional programming that allows you to do just that. This challenge will test your ability to implement a zip function in JavaScript that takes multiple arrays and returns a new array where each element is an array containing corresponding elements from the input arrays.
Problem Description
Your task is to implement a JavaScript function named zip that accepts a variable number of arrays as arguments. The function should return a new array where each element is itself an array. This inner array will contain the elements from the input arrays at the same index.
For example, if you zip [1, 2, 3] and ['a', 'b', 'c'], the result should be [[1, 'a'], [2, 'b'], [3, 'c']].
The zip function should stop when the shortest input array runs out of elements. If any of the input arrays are empty, the result should be an empty array.
Examples
Example 1:
Input: zip([1, 2, 3], ['a', 'b', 'c'])
Output: [[1, 'a'], [2, 'b'], [3, 'c']]
Explanation: The first element of the output is an array containing the first element from each input array. This continues until all elements are processed.
Example 2:
Input: zip([1, 2], ['a', 'b', 'c', 'd'])
Output: [[1, 'a'], [2, 'b']]
Explanation: The zip operation stops after the second element because the first input array ([1, 2]) has run out of elements.
Example 3:
Input: zip([1, 2, 3], [], ['a', 'b'])
Output: []
Explanation: One of the input arrays is empty, so the zip operation results in an empty array.
Example 4:
Input: zip([1, 2, 3])
Output: [[1], [2], [3]]
Explanation: When only one array is provided, each element of the output is an array containing just that single element.
Constraints
- The
zipfunction should accept any number of array arguments (including zero or one). - The input arrays can contain any data type (numbers, strings, booleans, objects, null, undefined, etc.).
- The function should not mutate the original input arrays.
- The performance of the
zipfunction should be efficient, ideally with a time complexity that is linear with respect to the total number of elements processed from the shortest array across all input arrays.
Notes
Consider how you will handle the case where no arrays are passed to the zip function. You might want to return an empty array in this scenario.
Think about how to iterate through the arrays simultaneously and efficiently collect the corresponding elements. The arguments object or the rest parameter syntax (...args) will be useful for handling a variable number of arguments.