Last active
November 15, 2015 10:27
-
-
Save hachinobu/2707a9fe39a49daa1b8a to your computer and use it in GitHub Desktop.
ArrayでGroupBy
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
import UIKit | |
public protocol Groupable { | |
func sameGroupAs(other: Self) -> Bool | |
} | |
extension CollectionType { | |
public typealias ItemType = Self.Generator.Element | |
public typealias Grouper = (ItemType, ItemType) -> Bool | |
public func groupBy(grouper: Grouper) -> [[ItemType]] { | |
var result: Array<Array<ItemType>> = [] | |
var previousItem: ItemType? | |
var group = [ItemType]() | |
for item in self { | |
defer { previousItem = item } | |
guard let previous = previousItem else { | |
group.append(item) | |
continue | |
} | |
if grouper(previous, item) { | |
group.append(item) | |
} | |
else { | |
result.append(group) | |
group = [ItemType]() | |
group.append(item) | |
} | |
} | |
result.append(group) | |
return result | |
} | |
} | |
extension CollectionType where Self.Generator.Element: Groupable { | |
public func group() -> [[Self.Generator.Element]] { | |
return self.groupBy { $0.sameGroupAs($1) } | |
} | |
} | |
extension CollectionType where Self.Generator.Element: Comparable { | |
public func uniquelyGroupBy(grouper: (Self.Generator.Element, Self.Generator.Element) -> Bool) -> [[Self.Generator.Element]] { | |
let sorted = self.sort() | |
return sorted.groupBy(grouper) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment