Created
September 15, 2016 21:25
-
-
Save thomasjonas/f99f48e278fd2dfe82edb2c6f7d6c365 to your computer and use it in GitHub Desktop.
intersperse with a jsx element
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. | |
* | |
* > _([1,2,3]).intersperse(0) | |
* [1,0,2,0,3] | |
*/ | |
function intersperse(arr, sep) { | |
if (arr.length === 0) { | |
return []; | |
} | |
return arr.slice(1).reduce((xs, x, idx) => { | |
const separator = (typeof sep === 'function') | |
? sep(idx) | |
: sep; | |
return xs.concat([separator, x]); | |
}, [arr[0]]); | |
} | |
// Example | |
var tags = item.tags.map(function(tag, i) { | |
return <Tag key={i} tag={item.tags[i]} />; | |
}; | |
tags = intersperse(tags, (idx) => { | |
return <span key={idx}>, </span> | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment