Last active
July 24, 2017 12:25
-
-
Save nikriek/1e1a3b7b694a420040030289e194641b to your computer and use it in GitHub Desktop.
Functional Reduce By Key
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
extension Array { | |
/// GroupBy that puts each element into a group of similiar elements denoted by an Equatable attribute, complexity: O(n) | |
func reduce<G: Equatable>(by key: (Element) -> (G)) -> [G: [Element]] { | |
return reduce([:], { (result, element) in | |
var groups = result | |
let group = key(element) | |
if let existingGroupElements = groups[group] { | |
groups[group] = existingGroupElements + [element] | |
} else { | |
groups[group] = [element] | |
} | |
return groups | |
}) | |
} | |
} | |
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
struct Post { | |
var title: String | |
var author: String | |
} | |
let posts = [ | |
Post(title: "Post 1", author: "Peter Parker"), | |
Post(title: "Post 3", author: "Clark Kent"), | |
Post(title: "Post 2", author: "Peter Parker") | |
] | |
let postsByAuthor = posts.reduce(by: { $0.author }) | |
/* | |
postsByAuthor: | |
[ | |
"Peter Parker": [ | |
Post(title: "Post 1", author: "Peter Parker"), | |
Post(title: "Post 2", author: "Peter Parker") | |
], | |
"Clark Kent": [ | |
Post(title: "Post 3", author: "Clark Kent") | |
] | |
] | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment