Created
February 7, 2024 06:13
-
-
Save kk-vv/ac872c814d715cc82917ff694d44b40f to your computer and use it in GitHub Desktop.
Convertto 2d array with raw cout or group by key
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 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