Created
February 6, 2015 14:24
-
-
Save tapi/325f06bca45dd799ffc9 to your computer and use it in GitHub Desktop.
A generic groupby function that should work similarily to ruby's
This file contains 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
/** | |
Group all items in a collection according to the value returned by a block. | |
:param: collection The collection whose items you want to group. | |
:param: groupBlock A block that returns a key for that value to be grouped by. | |
:returns: Returns a dictionary whose keys are the values returned by the groupBlock. | |
*/ | |
func groupBy<V, K : protocol<Hashable, Equatable>, C : _ExtensibleCollectionType where C.Generator.Element == V>(collection: C, groupBlock: (V) -> K) -> [K: [V]] { | |
typealias ValueGroup = [V] | |
var grouped = [K: ValueGroup]() | |
for value in collection { | |
var key = groupBlock(value) | |
var group = grouped[key] | |
if let existingGroup = group { | |
group = existingGroup + [value] | |
} | |
else { | |
group = [value] | |
} | |
grouped[key] = group | |
} | |
return grouped | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment