Last active
September 12, 2018 02:03
-
-
Save karwa/cafbd1531f7cb0d870b062ed92517b5d to your computer and use it in GitHub Desktop.
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
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