Last active
February 25, 2018 13:49
-
-
Save royling/471733d3a0dc42dac7a9 to your computer and use it in GitHub Desktop.
Interweave arrays
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
// inspired when reading https://leanpub.com/understandinges6/read#leanpub-auto-define-tags | |
// this is the behavior that template tags may interweave literals and subsitutions arrays | |
var interweave = (a, b) => { | |
let min = Math.min(a.length, b.length); | |
return Array.apply(null, Array(min)).reduce((result, value, index) => { | |
result.push(a[index], b[index]); | |
return result; | |
}, []).concat((a.length > min ? a : b).slice(min)); | |
}; | |
console.log(interweave([], [])); // => [] | |
console.log(interweave([], [4, 5])); // => [4, 5] | |
console.log(interweave([1, 2, 3], [])); // => [1, 2, 3] | |
console.log(interweave([1, 2, 3], [4, 5])); // => [1, 4, 2, 5, 3] | |
console.log(interweave([1], [4, 5])); // => [1, 4, 5] | |
console.log(interweave([1, 2], [4, 5])); // => [1, 4, 2, 5] | |
// demo with template strings | |
var echo = (literals, ...subs) => interweave(literals, subs).join(''); | |
var message = `world`; | |
console.log(echo `hello ${message}!`); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you for sharing this code. However I needed a way to 'stretch' the small array into the final one so I came up with this https://gist.github.com/solendil/d5b17b048579b00319363c0fe4d21a45.