Skip to content

Instantly share code, notes, and snippets.

@PandaSekh
Created May 6, 2021 09:37
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 PandaSekh/df9190f19999b57ef5bbd42371898a84 to your computer and use it in GitHub Desktop.
Save PandaSekh/df9190f19999b57ef5bbd42371898a84 to your computer and use it in GitHub Desktop.
ReactJS Intersperse with Typescript
/*
* intersperse: Return an array with the separator interspersed between
* each element of the input array.
*
* https://stackoverflow.com/questions/23618744/rendering-comma-separated-list-of-links
*
* > _([1,2,3]).intersperse(0)
* [1,0,2,0,3]
*
* This version is done in Typescript and supports React Elements.
*/
export default function Intersperse({
arr,
sep,
}: {
arr: Array<JSX.Element | string>;
sep: string | JSX.Element;
}): JSX.Element {
if (arr.length <= 1) return <></>;
const merged: JSX.Element | string = arr.reduce((prev: JSX.Element | string, curr: JSX.Element | string) => (
<>{[prev, sep, curr]}</>
));
return <>{merged}</>;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment