Created
December 26, 2015 14:16
-
-
Save johankj/a8cc1bb1eaa6e08ba945 to your computer and use it in GitHub Desktop.
A GroupBy method in Swift as seen in other languages
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
extension SequenceType where Generator.Element: Comparable { | |
func group() -> [[Generator.Element]] { | |
return self.group { $0 == $1 } | |
} | |
func group(by groupBy: (Generator.Element, Generator.Element) -> Bool) -> [[Generator.Element]] { | |
return self.reduce([]) { (xs, q) -> [[Generator.Element]] in | |
guard xs.count > 0 else { return [[q]] } | |
var xs = xs | |
let last = xs.count-1 | |
if groupBy(xs[last][0], q) { | |
xs[last].append(q) | |
return xs | |
} | |
xs.append([q]) | |
return xs | |
} | |
} | |
} | |
["a", "a", "a", "A", "A", "b", "c", "b"].group() // [["a", "a", "a"], ["A", "A"], ["b"], ["c"], ["b"]] | |
["a", "a", "a", "A", "A", "b", "c", "b"].group { a, b in a.lowercaseString == b.lowercaseString } // [["a", "a", "a", "A", "A"], ["b"], ["c"], ["b"]] | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment