Skip to content

Instantly share code, notes, and snippets.

@ppeelen
Last active June 9, 2021 14:35
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 ppeelen/4a02719f024c2d34464d618ff3a15fdb to your computer and use it in GitHub Desktop.
Save ppeelen/4a02719f024c2d34464d618ff3a15fdb to your computer and use it in GitHub Desktop.
Swift: Lazy filter with prefix. Check if occurrence of X happens more than Y times using filter
struct FooBar {
let state: Bool
func isTrue() -> Bool { state } // Called 1000 times
func isFalse() -> Bool { !state } // Called 92 times
}
let fooList = (0..<1000).compactMap { n in FooBar(state: Bool.random()) }
let start = CFAbsoluteTimeGetCurrent()
if fooList.filter({ $0.isTrue() }).count > 1 {
print("> 1")
} else {
print("<= 1")
}
let diff = CFAbsoluteTimeGetCurrent() - start
debugPrint("First one took: \(diff)") // 0.02408897876739502
let secondStart = CFAbsoluteTimeGetCurrent()
if fooList.lazy.filter({ $0.isFalse() }).prefix(20).count > 1 {
print("> 1")
} else {
print("<= 1")
}
let diff2 = CFAbsoluteTimeGetCurrent() - secondStart
debugPrint("Second one took: \(diff2)") // Took 0.0023419857025146484
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment