Last active
May 19, 2022 14:11
-
-
Save mackoj/80bf9bfcf10b535790ba35681c892e2e to your computer and use it in GitHub Desktop.
Extract duplicates from a RandomAccessCollection, Array, IndentifiedArray, etc...
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
import Foundation | |
extension RandomAccessCollection { | |
/// Extract duplicates from a RandomAccessCollection | |
/// | |
/// ```swift | |
/// let data = [User("jerem", amount: 567), User("jeff", amount: 124), User("jeff", amount: 567)] | |
/// let duplicateName = data.duplicates(\.name) | |
/// // duplicateName = [User("jeff", amount: 124), User("jeff", amount: 567)] | |
/// let duplicateAmount = data.duplicates(\.amount) | |
/// // duplicateName = [User("jeff", amount: 567), User("jerem", amount: 567)] | |
/// ``` | |
func duplicates<Output: Hashable>(by keyPath: KeyPath<Element, Output>) -> [Element] { | |
return self.lazy.reduce(into: [Output: (counter: Int, element: Element)]()) { partialResult, element in | |
let key = element[keyPath: keyPath] | |
let val = partialResult[key] | |
partialResult[key] = (counter: val?.counter ?? 0, element: val?.element ?? element) | |
}.filter { dictLine in | |
dictLine.value.counter > 1 | |
}.map { dictLine in | |
dictLine.value.element | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment