Last active
June 9, 2018 21:41
-
-
Save vhart/ce91b465baf053db62061efa3479b330 to your computer and use it in GitHub Desktop.
Filter3
This file contains hidden or 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
struct Filter<Object> { | |
let keyPath: PartialKeyPath<Object> | |
private let matcher: (Any) -> Bool | |
init<Type>(keyPath: KeyPath<Object, Type>, matcher: @escaping (Type) -> Bool) { | |
self.keyPath = keyPath | |
self.matcher = { value in | |
let typedValue = value as! Type | |
return matcher(typedValue) | |
} | |
} | |
func matchesAgainst(_ object: Object) -> Bool { | |
let value = object[keyPath: keyPath] | |
return matcher(value) | |
} | |
static func apply<T>(_ filters: [Filter<T>], to collection: [T]) -> [T] { | |
return collection.filter { object in | |
for filter in filters { | |
guard filter.matchesAgainst(object) else { return false } | |
} | |
return true | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment