Skip to content

Instantly share code, notes, and snippets.

@mklbtz
Last active September 2, 2017 21:00
Show Gist options
  • Save mklbtz/7181da7f3b5db7745817 to your computer and use it in GitHub Desktop.
Save mklbtz/7181da7f3b5db7745817 to your computer and use it in GitHub Desktop.
New array method: partition
// Here, I’ve added a function to Array called `partition`.
// In short, the function will partition the Array into a Dictionary based on a function
// which takes an Element of the Array and returns its corresponding Key into the Dictionary.
extension Array {
func partition<Key>(key: (Element)->Key) -> [Key: [Element]] {
var groups = [Key: [Element]]()
for element in self {
let key = key(element)
var group = groups[key] ?? [Element]()
group.append(element)
groups[key] = group
}
return groups
}
}
let nums = [1,2,3,4,5,6,7,8,9,10]
nums.partition { n in
n % 2 == 0 ? "even" : "odd"
}
// => ["odd": [1, 3, 5, 7, 9], "even": [2, 4, 6, 8, 10]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment