Skip to content

Instantly share code, notes, and snippets.

@slorber
Created February 13, 2020 08:46
Show Gist options
  • Save slorber/3ffd835e2ae6f4fc79c24b06bc72f221 to your computer and use it in GitHub Desktop.
Save slorber/3ffd835e2ae6f4fc79c24b06bc72f221 to your computer and use it in GitHub Desktop.
export const intersperse = <T>(arr: T[], separator: (n: number) => T): T[] =>
arr.flatMap(arr, (a, i) => i > 0 ? [separator(i-1), a] : [a]))
export const intersperse = <T>(arr: T[], separator: (n: number) => T): T[] =>
arr.reduce<T[]>((acc, currentElement, currentIndex) => {
const isLast = currentIndex === arr.length - 1;
return [
...acc,
currentElement,
...(isLast ? [] : [separator(currentIndex)]),
];
}, []);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment