Skip to content

Instantly share code, notes, and snippets.

@karwa
Last active September 12, 2018 02:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save karwa/cafbd1531f7cb0d870b062ed92517b5d to your computer and use it in GitHub Desktop.
Save karwa/cafbd1531f7cb0d870b062ed92517b5d to your computer and use it in GitHub Desktop.
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