Skip to content

Instantly share code, notes, and snippets.

@willbonney
Created February 13, 2026 00:11
Show Gist options
  • Select an option

  • Save willbonney/c6e81dbf6e670c50aa9136717c6ed042 to your computer and use it in GitHub Desktop.

Select an option

Save willbonney/c6e81dbf6e670c50aa9136717c6ed042 to your computer and use it in GitHub Desktop.
Ungrouped element batching w/ predicate
export const batchMessages = <T,>(
messages: T[],
shouldBeBatched: (
prevItem: T,
nextItem: T,
) => boolean,
): T[][] =>
messages?.reduce((acc: T[][], curr) => {
const processed = acc.length
const prevSubArr = acc[processed - 1]
const lastElInPrevSubArr = prevSubArr?.[prevSubArr?.length - 1]
if (prevSubArr != null && shouldBeBatched(lastElInPrevSubArr, curr)) {
prevSubArr.push(curr)
} else {
acc.push([curr])
}
return acc
}, [])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment