Last active
February 3, 2016 13:47
-
-
Save algal/62131fa44ec205a62826 to your computer and use it in GitHub Desktop.
groupBy
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
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