Skip to content

Instantly share code, notes, and snippets.

@matyasfodor
Last active September 30, 2023 05:50
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save matyasfodor/9ae9ee9a6c619c6752bc686f2baabbd1 to your computer and use it in GitHub Desktop.
Save matyasfodor/9ae9ee9a6c619c6752bc686f2baabbd1 to your computer and use it in GitHub Desktop.
ES6 Zip functions: zipShort and zipLong
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 ]]
@tanishqmanuja
Copy link

tanishqmanuja commented Apr 23, 2022

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 ?

@lemanschik
Copy link

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