Created
June 30, 2021 03:53
-
-
Save oshinko/bee28689426fad97bfddad08707535d1 to your computer and use it in GitHub Desktop.
How to zip arrays with JavaScript.
This file contains hidden or 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
/** | |
* const expected = [[0, 2], [1, 3]] | |
* const actual = [...zip([0, 1], [2, 3])] | |
* assert JSON.stringify(expected) === JSON.stringify(actual) | |
*/ | |
export function *zip(...arrays) { | |
try { | |
arrays[0] = [...arrays[0]] | |
} catch { | |
throw Error(`TypeError: First argument "${arrays[0]}" is not iterable`) | |
} | |
for (const i in arrays[0]) | |
yield arrays.map(array => array[i]) | |
} | |
export default { | |
zip | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment