Created
July 31, 2018 19:03
-
-
Save rsms/f539b6b607eb16c5c2f98af2eab2a751 to your computer and use it in GitHub Desktop.
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
| function zipmerge(/* ...lists */) { | |
| var lists = Array.prototype.slice.call(arguments) | |
| // find longest list | |
| var nlists = lists.length, maxlen = 0, i | |
| for (i = 0; i < nlists; i++) { | |
| maxlen = Math.max(arguments[i].length, maxlen) | |
| } | |
| // populate result | |
| var res = new Array(maxlen * nlists), L, listi, x, maxi = 0 | |
| for (listi = 0; listi < nlists; listi++) { | |
| L = lists[listi] | |
| for (i = 0; i < L.length; ++i) { | |
| x = listi + (i * nlists) | |
| res[x] = L[i] | |
| if (x > maxi) { | |
| maxi = x | |
| } | |
| } | |
| } | |
| res.length = maxi + 1 | |
| return res | |
| } | |
| console.log( | |
| zipmerge( | |
| [1, 2, 3, 4], | |
| [10, 20, 30, 40], | |
| ['a','b','c','d'] | |
| ) | |
| ) | |
| // [1, 10, "a", 2, 20, "b", 3, 30, "c", 4, 40, "d"] | |
| console.log( | |
| zipmerge( | |
| [1, 2, 3, 4], | |
| ['a'] | |
| ) | |
| ) | |
| // [1, "a", 2, empty, 3, empty, 4] | |
| console.log( | |
| zipmerge( | |
| [1, 2, 3, 4], | |
| [10, 20, 30 ], | |
| ['a','b','c','d'] | |
| ) | |
| ) | |
| // [1, 10, "a", 2, 20, "b", 3, 30, "c", 4, <empty>, "d"] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment