Created
November 2, 2021 01:08
-
-
Save Oaphi/1be378a3b03fed1b621156903411b5e2 to your computer and use it in GitHub Desktop.
Interleave an array with a repeating element
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 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