Skip to content

Instantly share code, notes, and snippets.

@algal
Last active February 3, 2016 13:47
Show Gist options
  • Save algal/62131fa44ec205a62826 to your computer and use it in GitHub Desktop.
Save algal/62131fa44ec205a62826 to your computer and use it in GitHub Desktop.
groupBy
func groupBy<T>(equivalent:(a:T,b:T)->Bool, items:[T]) -> [[T]] {
var lastItem:T? = nil
var groups:[[T]] = []
var currentGroup:[T] = []
for item in items {
if lastItem == nil {
// first item
currentGroup.append(item)
}
else {
// same kind of item
if equivalent(a: item,b: lastItem!) {
currentGroup.append(item)
}
// new kind of item
else {
// tie off old item
groups.append(currentGroup)
currentGroup = []
currentGroup.append(item)
}
}
lastItem = item
}
// tie off last group
groups.append(currentGroup)
return groups
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment