Last active
December 31, 2024 17:16
-
-
Save dabrahams/5eb3033a76b9e2277511e5931e7c7876 to your computer and use it in GitHub Desktop.
Sorting generic collections when sortable. It can be hard to get stable test results for generic components that use hashing or parallelism. Use sortable elements and applying sortedIfPossible strategically can help
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
func compare<T: Comparable, U>(_ x: T, _ y: U) -> Bool { | |
return x < (y as! T) | |
} | |
extension Collection { | |
func sortedIfPossible() -> [Element] { | |
if isEmpty { return []} | |
if Element.self as Any.Type is any Comparable.Type { | |
return self.sorted { | |
let l = $0 as! any Comparable | |
return compare(l, $1) | |
} | |
} | |
if self.first! as Any is (any Comparable, any Comparable) { | |
return self.sorted { | |
let l = $0 as! (any Comparable, any Comparable) | |
let r = $1 as! (any Comparable, any Comparable) | |
return compare(l.0, r.0) || !compare(r.0, l.0) && compare(l.1, r.1) | |
} | |
} | |
if self.first! as Any is (any Comparable, Any) { | |
return self.sorted { | |
let l = $0 as! (any Comparable, Any) | |
let r = $1 as! (Any, Any) | |
return compare(l.0, r.0) | |
} | |
} | |
return Array(self) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment