Created
June 27, 2020 17:24
-
-
Save davidchambers/f4b58645b752df0295dc461513c1824b to your computer and use it in GitHub Desktop.
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
//# groupBy :: (a -> b) -> Array a -> Array (Array a) | |
//. | |
//. Group the given elements in accordance with the given comparator. | |
//. | |
//. > groupBy (x => x % 3) ([1, 2, 3, 4, 5, 6, 7, 8, 9]) | |
//. [[1, 4, 7], [2, 5, 8], [3, 6, 9]] | |
const groupBy = f => xs => { | |
const groups = []; | |
const ys = []; | |
xs.forEach (x => { | |
const y = f (x); | |
const idx = ys.indexOf (y); | |
if (idx < 0) { | |
ys.push (y); | |
groups.push ([x]); | |
} else { | |
groups[idx].push (x); | |
} | |
}); | |
return groups; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment