Last active
September 30, 2023 05:50
-
-
Save matyasfodor/9ae9ee9a6c619c6752bc686f2baabbd1 to your computer and use it in GitHub Desktop.
ES6 Zip functions: zipShort and zipLong
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function _zip(func, args) { | |
const iterators = args.map(arr => arr[Symbol.iterator]()); | |
let iterateInstances = iterators.map((i) => i.next()); | |
ret = [] | |
while(iterateInstances[func](it => !it.done)) { | |
ret.push(iterateInstances.map(it => it.value)); | |
iterateInstances = iterators.map((i) => i.next()); | |
} | |
return ret; | |
} | |
const zipShort = (...args) => _zip('every', args); | |
const zipLong = (...args) => _zip('some', args); | |
zipShort([1,2,3], [4,5,6, 7]) | |
// [ | |
// [ 1, 4 ], | |
// [ 2, 5 ], | |
// [ 3, 6 ] ] | |
zipLong([1,2,3], [4,5,6, 7]) | |
// [ | |
// [ 1, 4 ], | |
// [ 2, 5 ], | |
// [ 3, 6 ], | |
// [ undefined, 7 ]] |
Just my 5 cent if i need to know while coding that i need Long or Short then this does not help a lot as if i would have 2 arrays that i want to zip i would always need to check if the length matches when i do that i can directly slice 2 identical long arrays and even fill.
so https://gist.github.com/renaudtertrais/25fc5a2e64fe5d0e86894094c6989e10 is better when you need to add checks anyway.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Very useful for array manipulation, just wanted to ask if there is a way we can pass a value to fill in place of undefined in case of zipLong ?