Skip to content

Instantly share code, notes, and snippets.

@ddgromit
Created December 5, 2017 01:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ddgromit/2a15e7f4cfea1036436330f76a75f3a2 to your computer and use it in GitHub Desktop.
Save ddgromit/2a15e7f4cfea1036436330f76a75f3a2 to your computer and use it in GitHub Desktop.
Groups adjacent elements of an array that satisfy an equality function.
/* @flow */
function groupByAdjacent<T>(arr: Array<T>, eq: (T, T) => boolean): Array<Array<T>> {
return arr.reduce((prev, curr) => {
if (prev.length && eq(curr, prev[prev.length - 1][0])) {
prev[prev.length - 1].push(curr);
} else {
prev.push([curr]);
}
return prev;
}, []);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment