forked from aleksey-ios-dev/Predicate
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPredicate+LogicalOperations.swift
More file actions
56 lines (42 loc) · 1.44 KB
/
Predicate+LogicalOperations.swift
File metadata and controls
56 lines (42 loc) · 1.44 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
//
// Created by Oleksii Chernysh on 06.11.17.
// Copyright © 2017 Oleksii Chernysh. All rights reserved.
//
import Foundation
// Primitive
func &&<T>(left: Predicate<T>, right: Predicate<T>) -> Predicate<T> {
return Predicate<T> { left.check($0) && right.check($0) }
}
func ||<T>(left: Predicate<T>, right: Predicate<T>) -> Predicate<T> {
return Predicate<T> { left.check($0) || right.check($0) }
}
func !=<T>(left: Predicate<T>, right: Predicate<T>) -> Predicate<T> {
return Predicate<T> { left.check($0) != right.check($0) }
}
prefix func !<T>(left: Predicate<T>) -> Predicate<T> {
return Predicate<T> { !left.check($0) }
}
// Composite
func any<T>(_ predicates: [Predicate<T>]) -> Predicate<T> {
return predicates.reduce(Predicate { _ in false }, { result, element in
return result || element
})
}
func all<T>(_ predicates: [Predicate<T>]) -> Predicate<T> {
return predicates.reduce(Predicate { _ in true }, { result, element in
return result && element
})
}
func none<T>(_ predicates: [Predicate<T>]) -> Predicate<T> {
return !any(predicates)
}
// Higher order
func any<T, U>(_ rule: @escaping (U) -> Predicate<T>, _ values: [U]) -> Predicate<T> {
return any(values.map { rule($0) })
}
func all<T, U>(_ rule: (U) -> Predicate<T>, _ values: [U]) -> Predicate<T> {
return all(values.map { rule($0) })
}
func none<T, U>(_ rule: @escaping (U) -> Predicate<T>, _ values: [U]) -> Predicate<T> {
return !any(rule, values)
}