Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
enum CountPredicate {
case greaterThan(_ n: Int)
case equalTo(_ n: Int)
}
extension Collection {
func count(is predicate: CountPredicate) -> Bool {
switch predicate {
case .equalTo(let val):
return _countIsEqualTo(val)
case .greaterThan(let val):
return _countIsGreaterThan(val)
}
}
private func _countIsEqualTo(_ n: Int) -> Bool {
var tmp = 0
for _ in self {
tmp += 1
if tmp > n { return false } // Seen more than `n` elements. Not equal.
}
return tmp == n
}
private func _countIsGreaterThan(_ n: Int) -> Bool {
var tmp = 0
for _ in self {
tmp += 1
if tmp > n { return true } // Seen more than `n` elements. count > n.
}
return n < 0
}
}
// RAC.count is O(1) anyway.
extension RandomAccessCollection {
func count(is predicate: CountPredicate) -> Bool {
switch predicate {
case .greaterThan(let val): return self.count > val
case .equalTo(let val): return self.count == val
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.