Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@royling
Last active February 25, 2018 13:49
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save royling/471733d3a0dc42dac7a9 to your computer and use it in GitHub Desktop.
Save royling/471733d3a0dc42dac7a9 to your computer and use it in GitHub Desktop.
Interweave arrays
// 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}!`);
@solendil
Copy link

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment