Skip to content

Instantly share code, notes, and snippets.

@aschyiel
Last active August 14, 2026 23:25
Show Gist options
  • Select an option

  • Save aschyiel/d8c7f4b5454ddcde16c46e4112c8bc0a to your computer and use it in GitHub Desktop.

Select an option

Save aschyiel/d8c7f4b5454ddcde16c46e4112c8bc0a to your computer and use it in GitHub Desktop.
TSX Component to conditionally add commas and line-breaks to an informal list of items within a tooltip, etc. - a tedious task that is easy to get wrong or add extra noise at the end if you're not careful. uses the lodash floatten + zip trick which comes in handy every once in a while that is easy to forget as a combo.
import _ from 'lodash'
import type { ReactNode } from 'react'
/**
* A somewhat common task we find ourselves in is to conditionally add commas and
* line-breaks to an informal list of items within a tooltip, etc.
*/
export const intersperse_separator = (
input: ReactNode[],
options: { separator?: string; inject_br?: boolean } = {}
) => {
const { separator = ',', inject_br = false } = options
input = _.filter(input, _.identity) as ReactNode[]
if (_.isEmpty(input)) {
return null
}
const len = input.length
const commas = _.times(len - 1, (_i) => (
<span>
{separator}
{inject_br ? <br /> : null}
</span>
))
return _.map(_.flatten(_.zip(input, commas)), (it, idx: number) => (
<span key={`interspersed-${idx}`}>{it}</span>
))
}
export default intersperse_separator
@aschyiel

Copy link
Copy Markdown
Author

cleaned up via claude code blha lbah blah

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment