Skip to content

Instantly share code, notes, and snippets.

@Oaphi
Created November 2, 2021 01:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Oaphi/1be378a3b03fed1b621156903411b5e2 to your computer and use it in GitHub Desktop.
Save Oaphi/1be378a3b03fed1b621156903411b5e2 to your computer and use it in GitHub Desktop.
Interleave an array with a repeating element
const interleave = <T, U>(arr: T[], inserted: U) => {
let insertions = 0;
return arr.flatMap((val, idx) => {
const isEven = (idx + insertions) % 2;
if(isEven) insertions += 1;
return isEven ? [inserted, val] : val;
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment