Re:Zip Function Solution: Haskell, Elixir, JavaScript, Pytho...
by universa1 on Thursday November 10, 2022 @02:14AM
(#33543243)
That was my quick reaction as well... I think it would need something like the python example below, where you first check the lengths of the two arrays/lists, and then iterate over that, and not directly over the length of the first list.
iter_limit = Math.min(ls1.length, ls2.length);
for(let i = 0; i < iter_limit; i++)...
Re:Zip Function Solution: Haskell, Elixir, JavaScript, Pytho...
by chrisco255 on Thursday November 10, 2022 @06:12AM
(#33544887)
function zip(arr_a, arr_b) {
const len = arr_a.length < arr_b.length ? arr_a.length : arr_b.length;
return arr_a.slice(0, len).map((el, idx) => [el, arr_b[idx]]);
}
Re:Zip Function Solution: Haskell, Elixir, JavaScript, Pytho...
by m-r-r on Thursday November 10, 2022 @07:23AM
(#33545411)
Yes, the JavaScript implementation doesn't works if the second array contains 'false', 'null', 'undefined', '0' or 'NaN'.
Here is my implementation of the 'zip' function in modern JavaScript. It is similar to the Vlang version, but it is generic over the number of arrays :
const zip = (...arrays) => {
const length = Math.min(...arrays.map((array) => array.length));
return Array.from({ length }, (_, i) => arrays.map((array) => array[i]));
};
The minimum length approach seams to be the better one. (Without having it run anywhere.)