Skip to content

Instantly share code, notes, and snippets.

@kk-vv
Created February 7, 2024 06:13
Show Gist options
  • Save kk-vv/ac872c814d715cc82917ff694d44b40f to your computer and use it in GitHub Desktop.
Save kk-vv/ac872c814d715cc82917ff694d44b40f to your computer and use it in GitHub Desktop.
Convertto 2d array with raw cout or group by key
extension Array {
func convertTo2DArray(rawCount: Int) -> [[Element]] {
let array = stride(from: 0, to: self.count, by: rawCount).map { (index) -> [Element] in
if (index + rawCount) > self.count {
return Array(self[index...])
} else {
return Array(self[index..<index + rawCount])
}
}
return array
}
func group<GroupingType: Hashable>(by key: (Iterator.Element) -> GroupingType) -> [GroupingType: [Iterator.Element]] {
var groups: [GroupingType: [Iterator.Element]] = [:]
forEach { element in
let key = key(element)
if case nil = groups[key]?.append(element) {
groups[key] = [element]
}
}
return groups
}
func getMax(count: Int) -> Self {
if self.count < count {
return self
} else {
return Array(self[0..<count])
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment