Created
May 6, 2021 09:37
-
-
Save PandaSekh/df9190f19999b57ef5bbd42371898a84 to your computer and use it in GitHub Desktop.
ReactJS Intersperse with Typescript
This file contains 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
/* | |
* 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