Last active
September 2, 2017 21:00
-
-
Save mklbtz/7181da7f3b5db7745817 to your computer and use it in GitHub Desktop.
New array method: partition
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
// 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