Created
December 5, 2017 01:33
-
-
Save ddgromit/2a15e7f4cfea1036436330f76a75f3a2 to your computer and use it in GitHub Desktop.
Groups adjacent elements of an array that satisfy an equality function.
This file contains hidden or 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
/* @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