├── .github └── workflows │ └── swift.yml ├── .gitignore ├── .vscode └── tasks.json ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── LICENSE ├── Package.swift ├── README.md ├── Sources └── Predicate │ └── Predicate.swift └── Tests └── PredicateTests └── Tests.swift /.github/workflows/swift.yml: -------------------------------------------------------------------------------- 1 | name: Swift 2 | 3 | on: 4 | push: 5 | branches: [ master ] 6 | pull_request: 7 | branches: [ master ] 8 | 9 | jobs: 10 | build: 11 | 12 | runs-on: macos-latest 13 | 14 | steps: 15 | - uses: actions/checkout@v2 16 | - name: Build 17 | run: swift build -v 18 | - name: Run tests 19 | run: swift test -v 20 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | /.build 3 | /Packages 4 | /*.xcodeproj 5 | DerivedData/ 6 | .swiftpm -------------------------------------------------------------------------------- /.vscode/tasks.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "2.0.0", 3 | "tasks": [ 4 | { 5 | "label": "swift-build", 6 | "type": "shell", 7 | "command": "swift build", 8 | "group": { 9 | "kind": "build", 10 | "isDefault": true 11 | }, 12 | "presentation": { 13 | "reveal": "silent", 14 | "clear": true 15 | } 16 | }, 17 | { 18 | "label": "swift-test", 19 | "type": "shell", 20 | "command": "swift test", 21 | "group": { 22 | "kind": "test", 23 | "isDefault": true 24 | } 25 | } 26 | ] 27 | } -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as 6 | contributors and maintainers pledge to making participation in our project and 7 | our community a harassment-free experience for everyone, regardless of age, body 8 | size, disability, ethnicity, sex characteristics, gender identity and expression, 9 | level of experience, education, socio-economic status, nationality, personal 10 | appearance, race, religion, or sexual identity and orientation. 11 | 12 | ## Our Standards 13 | 14 | Examples of behavior that contributes to creating a positive environment 15 | include: 16 | 17 | * Using welcoming and inclusive language 18 | * Being respectful of differing viewpoints and experiences 19 | * Gracefully accepting constructive criticism 20 | * Focusing on what is best for the community 21 | * Showing empathy towards other community members 22 | 23 | Examples of unacceptable behavior by participants include: 24 | 25 | * The use of sexualized language or imagery and unwelcome sexual attention or 26 | advances 27 | * Trolling, insulting/derogatory comments, and personal or political attacks 28 | * Public or private harassment 29 | * Publishing others' private information, such as a physical or electronic 30 | address, without explicit permission 31 | * Other conduct which could reasonably be considered inappropriate in a 32 | professional setting 33 | 34 | ## Our Responsibilities 35 | 36 | Project maintainers are responsible for clarifying the standards of acceptable 37 | behavior and are expected to take appropriate and fair corrective action in 38 | response to any instances of unacceptable behavior. 39 | 40 | Project maintainers have the right and responsibility to remove, edit, or 41 | reject comments, commits, code, wiki edits, issues, and other contributions 42 | that are not aligned to this Code of Conduct, or to ban temporarily or 43 | permanently any contributor for other behaviors that they deem inappropriate, 44 | threatening, offensive, or harmful. 45 | 46 | ## Scope 47 | 48 | This Code of Conduct applies both within project spaces and in public spaces 49 | when an individual is representing the project or its community. Examples of 50 | representing a project or community include using an official project e-mail 51 | address, posting via an official social media account, or acting as an appointed 52 | representative at an online or offline event. Representation of a project may be 53 | further defined and clarified by project maintainers. 54 | 55 | ## Enforcement 56 | 57 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 58 | reported by contacting the project team at oliveratkinson@me.com. All 59 | complaints will be reviewed and investigated and will result in a response that 60 | is deemed necessary and appropriate to the circumstances. The project team is 61 | obligated to maintain confidentiality with regard to the reporter of an incident. 62 | Further details of specific enforcement policies may be posted separately. 63 | 64 | Project maintainers who do not follow or enforce the Code of Conduct in good 65 | faith may face temporary or permanent repercussions as determined by other 66 | members of the project's leadership. 67 | 68 | ## Attribution 69 | 70 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, 71 | available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html 72 | 73 | [homepage]: https://www.contributor-covenant.org 74 | 75 | For answers to common questions about this code of conduct, see 76 | https://www.contributor-covenant.org/faq 77 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # How to contribute 2 | 3 | There are a just a few small guidelines you need to follow. 4 | 5 | ## Submitting a patch 6 | 7 | 1. It's generally best to start by opening a new issue describing the bug or feature you're intending to fix. Even if you think it's relatively minor, it's helpful to know what people are working on. Mention in the initial issue that you are planning to work on that bug or feature so that it can be assigned to you. 8 | 2. It's important that each group of changes be done in separate branches in order to ensure that a pull request only includes the commits related to that bug or feature. 9 | 3. Any changes should always be accompanied by tests. The project already has good test coverage, so look at some of the existing tests if you're unsure how to go about it. 10 | 4. Do your best to have well-formed commit messages for each change. This provides consistency throughout the project, and ensures that commit messages are able to be formatted properly by various git tools. See: http://chris.beams.io/posts/git-commit/ 11 | 5. Finally, push the commits and submit a pull request. 12 | 13 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2018 Oliver Atkinson 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /Package.swift: -------------------------------------------------------------------------------- 1 | // swift-tools-version:4.2 2 | // The swift-tools-version declares the minimum version of Swift required to build this package. 3 | 4 | import PackageDescription 5 | 6 | let package = Package( 7 | name: "Predicate", 8 | products: [ 9 | .library(name: "Predicate", targets: [ "Predicate" ]), 10 | ], 11 | targets: [ 12 | .target(name: "Predicate", dependencies: [ ]), 13 | .testTarget(name: "PredicateTests", dependencies: [ "Predicate" ]), 14 | ] 15 | ) 16 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Predicate 2 | 3 | [![Swift 5.2](https://img.shields.io/badge/swift-5.2-ED523F.svg?style=flat)](https://swift.org/download/) 4 | [![SPM](https://img.shields.io/badge/swift-SPM-ED523F.svg?style=flat)](https://swift.org/package-manager/) 5 | ![SPM](https://img.shields.io/badge/os-linux-lightgrey.svg?style=flat) 6 | ![macOS](https://img.shields.io/badge/os-macOS-lightgrey.svg?style=flat) 7 | [![Licence](https://img.shields.io/badge/License-MIT-yellow.svg?style=flat)](LICENCE) 8 | 9 | Predicate Composition 10 | 11 | ## API 12 | 13 | ### Equals 14 | ```swift 15 | public func == (block: @escaping (Root) -> Value, value: Value) -> (Root) -> Bool where Value : Equatable 16 | public func != (block: @escaping (Root) -> Value, value: Value) -> (Root) -> Bool where Value : Equatable 17 | ``` 18 | 19 | #### Example 20 | ```swift 21 | users.filter(\.name == "Milos") 22 | users.filter(\.name != "Ste") 23 | ``` 24 | 25 | ### Less Than & More Than 26 | ```swift 27 | public func < (block: @escaping (Root) -> Value, value: Value) -> (Root) -> Bool where Value : Comparable 28 | public func > (block: @escaping (Root) -> Value, value: Value) -> (Root) -> Bool where Value : Comparable 29 | public func <= (block: @escaping (Root) -> Value, value: Value) -> (Root) -> Bool where Value : Comparable 30 | public func >= (block: @escaping (Root) -> Value, value: Value) -> (Root) -> Bool where Value : Comparable 31 | ``` 32 | 33 | #### Example 34 | ```swift 35 | users.filter(\.age > 25) 36 | users.filter(\.age <= 55) 37 | ``` 38 | 39 | ### Similar to 40 | 41 | ```swift 42 | public func << (block: @escaping (Root) -> S.Element, value: S) -> (Root) -> Bool where S : Sequence, S.Element : Equatable 43 | public func ~= (block: @escaping (Root) -> String, regex: Regex) -> (Root) -> Bool 44 | public func == (block: @escaping (Root) -> Value, value: (Value, Value)) -> (Root) -> Bool where Value : FloatingPoint 45 | public func ± (number: Value, accuracy: Value) -> (Value, Value) where Value : FloatingPoint 46 | ``` 47 | 48 | #### Example 49 | 50 | - `<<` sequence contains 51 | - `±` comparing floating point numbers to a degree of accuracy 52 | - `~=` Regex 53 | 54 | ```swift 55 | users.filter(\.age << 30...35) 56 | users.filter(\.age << [ 30, 32, 34 ]) 57 | users.filter(\.weight == 85 ± 4 58 | users.filter(\.name ~= "o(s|ah)$") 59 | ``` 60 | 61 | ### Boolean Logic 62 | 63 | ```swift 64 | public prefix func ! (block: @escaping (Root) -> Bool) -> (Root) -> Bool 65 | public func && (lhs: @autoclosure @escaping () -> Bool, rhs: @escaping (Root) -> Bool) -> (Root) -> Bool 66 | public func || (lhs: @autoclosure @escaping () -> Bool, rhs: @escaping (Root) -> Bool) -> (Root) -> Bool 67 | public func && (lhs: @escaping (Root) -> Bool, rhs: @autoclosure @escaping () -> Bool) -> (Root) -> Bool 68 | public func || (lhs: @escaping (Root) -> Bool, rhs: @autoclosure @escaping () -> Bool) -> (Root) -> Bool 69 | public func && (lhs: @escaping (Root) -> Bool, rhs: @escaping (Root) -> Bool) -> (Root) -> Bool 70 | public func || (lhs: @escaping (Root) -> Bool, rhs: @escaping (Root) -> Bool) -> (Root) -> Bool 71 | ``` 72 | 73 | #### Example 74 | 75 | ```swift 76 | users.filter(\.isClearToFly && \.name == "Noah") 77 | users.filter(\.age > 30 && \.name != "Noah") 78 | ``` 79 | 80 | # Installation 81 | 82 | ## SwiftPM: 83 | 84 | ```swift 85 | package.append(.package(url: "https://github.com/ollieatkinson/Predicate", from: "1.0.0")) 86 | ``` 87 | -------------------------------------------------------------------------------- /Sources/Predicate/Predicate.swift: -------------------------------------------------------------------------------- 1 | import Foundation 2 | 3 | public func == (block: @escaping (Root) -> Value, value: Value) -> (Root) -> Bool where Value: Equatable { 4 | return { block($0) == value } 5 | } 6 | 7 | public func != (block: @escaping (Root) -> Value, value: Value) -> (Root) -> Bool where Value: Equatable { 8 | return { block($0) != value } 9 | } 10 | 11 | public func < (block: @escaping (Root) -> Value, value: Value) -> (Root) -> Bool where Value: Comparable { 12 | return { block($0) < value } 13 | } 14 | 15 | public func > (block: @escaping (Root) -> Value, value: Value) -> (Root) -> Bool where Value: Comparable { 16 | return { block($0) > value } 17 | } 18 | 19 | public func <= (block: @escaping (Root) -> Value, value: Value) -> (Root) -> Bool where Value: Comparable { 20 | return { block($0) <= value } 21 | } 22 | 23 | public func >= (block: @escaping (Root) -> Value, value: Value) -> (Root) -> Bool where Value: Comparable { 24 | return { block($0) >= value } 25 | } 26 | 27 | public prefix func ! (block: @escaping (Root) -> Bool) -> (Root) -> Bool { 28 | return { !block($0) } 29 | } 30 | 31 | public func && (lhs: @escaping @autoclosure () -> Bool, rhs: @escaping (Root) -> Bool) -> (Root) -> Bool { 32 | return { lhs() && rhs($0) } 33 | } 34 | 35 | public func || (lhs: @escaping @autoclosure () -> Bool, rhs: @escaping (Root) -> Bool) -> (Root) -> Bool { 36 | return { lhs() || rhs($0) } 37 | } 38 | 39 | public func && (lhs: @escaping (Root) -> Bool, rhs: @escaping @autoclosure () -> Bool) -> (Root) -> Bool { 40 | return { lhs($0) && rhs() } 41 | } 42 | 43 | public func || (lhs: @escaping (Root) -> Bool, rhs: @escaping @autoclosure () -> Bool) -> (Root) -> Bool { 44 | return { lhs($0) || rhs() } 45 | } 46 | 47 | public func && (lhs: @escaping (Root) -> Bool, rhs: @escaping (Root) -> Bool) -> (Root) -> Bool { 48 | return { lhs($0) && rhs($0) } 49 | } 50 | 51 | public func || (lhs: @escaping (Root) -> Bool, rhs: @escaping (Root) -> Bool) -> (Root) -> Bool { 52 | return { lhs($0) || rhs($0) } 53 | } 54 | 55 | // MARK:- Sequence 56 | 57 | public func << (block: @escaping (Root) -> S.Element, value: S) -> (Root) -> Bool where S: Sequence, S.Element: Equatable { 58 | return { value.contains(block($0)) } 59 | } 60 | 61 | // MARK:- Regex 62 | 63 | public func ~= (block: @escaping (Root) -> String, regex: Regex) -> (Root) -> Bool { 64 | return { block($0).range(of: regex.pattern, options: regex.options) != nil } 65 | } 66 | 67 | public struct Regex { 68 | 69 | public let pattern: String 70 | public let options: NSString.CompareOptions 71 | 72 | public init(pattern: String, options: NSString.CompareOptions) { 73 | self.pattern = pattern 74 | self.options = options.union(.regularExpression) 75 | } 76 | 77 | } 78 | 79 | extension Regex: ExpressibleByStringLiteral { 80 | 81 | public init(stringLiteral value: String) { 82 | self.init(pattern: value, options: .regularExpression) 83 | } 84 | 85 | public init(unicodeScalarLiteral value: String) { 86 | self.init(pattern: value, options: .regularExpression) 87 | } 88 | 89 | public init(extendedGraphemeClusterLiteral value: String) { 90 | self.init(pattern: value, options: .regularExpression) 91 | } 92 | 93 | } 94 | 95 | public func == (block: @escaping (Root) -> Value, value: (Value, Value)) -> (Root) -> Bool where Value: FloatingPoint { 96 | return { abs(block($0) - value.0) < value.1 } 97 | } 98 | 99 | infix operator ± : NilCoalescingPrecedence 100 | 101 | public func ± (number: Value, accuracy: Value) -> (Value, Value) where Value: FloatingPoint { 102 | return (number, accuracy) 103 | } 104 | -------------------------------------------------------------------------------- /Tests/PredicateTests/Tests.swift: -------------------------------------------------------------------------------- 1 | import XCTest 2 | import Predicate 3 | 4 | struct User: Hashable { 5 | let name: String 6 | let age: Int 7 | let weight: Float 8 | let isClearToFly: Bool 9 | } 10 | 11 | extension Sequence where Element: Hashable { 12 | var set: Set { .init(self) } 13 | } 14 | 15 | final class PredicateTests: XCTestCase { 16 | 17 | private var sut: [User]! 18 | 19 | override func setUp() { 20 | super.setUp() 21 | 22 | let Milos = User(name: "Milos", age: 32, weight: 78.2, isClearToFly: true) 23 | let Noah = User(name: "Noah", age: 38, weight: 82.1, isClearToFly: false) 24 | let Ste = User(name: "Ste", age: 36, weight: 85.8, isClearToFly: false) 25 | 26 | sut = [ Milos, Noah, Ste ] 27 | 28 | } 29 | 30 | public func XCTAssertUsersEqual( 31 | _ expression1: @autoclosure () throws -> S, 32 | _ expression2: String..., 33 | message: @autoclosure () -> String = "", 34 | file: StaticString = #file, 35 | line: UInt = #line 36 | ) rethrows where S: Sequence, S.Element == User { 37 | try XCTAssertUsersEqual(try expression1(), Array(expression2), message(), file: file, line: line) 38 | } 39 | 40 | public func XCTAssertUsersEqual( 41 | _ expression1: @autoclosure () throws -> S, 42 | _ expression2: @autoclosure () throws -> [String], 43 | _ message: @autoclosure () -> String = "", 44 | file: StaticString = #file, 45 | line: UInt = #line 46 | ) rethrows where S: Sequence, S.Element == User { 47 | XCTAssertEqual(try expression1().map(\.name), Array(try expression2()), message(), file: file, line: line) 48 | } 49 | 50 | func test_filter_string_equal() { 51 | XCTAssertUsersEqual(sut.filter(\.name == "Milos"), "Milos") 52 | } 53 | 54 | func test_filter_string_notEqual() { 55 | XCTAssertUsersEqual(sut.filter(\.name != "Milos"), "Noah", "Ste") 56 | } 57 | 58 | func test_filter_intComparison() { 59 | XCTAssertUsersEqual(sut.filter(\.age > 33), "Noah", "Ste") 60 | XCTAssertUsersEqual(sut.filter(\.age >= 36), "Noah", "Ste") 61 | } 62 | 63 | func test_filter_floatComparison() { 64 | XCTAssertUsersEqual(sut.filter(\.weight < 85), "Milos", "Noah") 65 | XCTAssertUsersEqual(sut.filter(\.weight <= 82.1), "Milos", "Noah") 66 | } 67 | 68 | func test_filter_float_equals_with_accuracy() { 69 | XCTAssertUsersEqual(sut.filter(\.weight == 85 ± 4), "Noah", "Ste") 70 | XCTAssertUsersEqual(sut.filter(\.weight == 82.1 ± 3), "Noah") 71 | } 72 | 73 | func test_filter_included_range() { 74 | XCTAssertUsersEqual(sut.filter(\.age << (30...35)), "Milos") 75 | } 76 | 77 | func test_filter_included_array() { 78 | XCTAssertUsersEqual(sut.filter(\.age << [ 30, 32, 34 ]), "Milos") 79 | } 80 | 81 | func test_filter_float() { 82 | XCTAssertUsersEqual(sut.filter(\.weight == 78.2), "Milos") 83 | } 84 | 85 | func test_filter_boolean() { 86 | XCTAssertUsersEqual(sut.filter(\.isClearToFly == false), [ "Noah", "Ste" ]) 87 | XCTAssertUsersEqual(sut.filter(\.isClearToFly), [ "Milos" ]) 88 | XCTAssertUsersEqual(sut.filter(!\.isClearToFly), [ "Noah", "Ste" ]) 89 | } 90 | 91 | func test_filter_and() { 92 | XCTAssertUsersEqual(sut.filter(!\.isClearToFly && \.name == "Noah"), "Noah") 93 | } 94 | 95 | func test_filter_or() { 96 | XCTAssertUsersEqual(sut.filter(!\.isClearToFly || \.name == "Milos"), "Milos", "Noah", "Ste") 97 | } 98 | 99 | func test_filter_not() { 100 | XCTAssertUsersEqual(sut.filter(!\.isClearToFly), "Noah", "Ste") 101 | } 102 | 103 | func test_filter_chain() { 104 | XCTAssertUsersEqual(sut.filter(!\.isClearToFly).filter(\.name == "Noah"), "Noah") 105 | } 106 | 107 | func test_filter_regex() { 108 | XCTAssertUsersEqual(sut.filter(\.name ~= "o(s|ah)$"), "Milos", "Noah") 109 | } 110 | 111 | func test_filter_regexCaseInsensitive() { 112 | XCTAssertUsersEqual(sut.filter(\.name ~= Regex(pattern: "O(S|AH)$", options: .caseInsensitive)), "Milos", "Noah") 113 | } 114 | 115 | func test_prefixWhile() { 116 | XCTAssertUsersEqual(sut.prefix(while: \.weight < 85), "Milos", "Noah") 117 | } 118 | 119 | func test_dropWhile() { 120 | XCTAssertUsersEqual(sut.drop(while: \.age < 35), "Noah", "Ste") 121 | } 122 | 123 | func test_first() { 124 | XCTAssertEqual(sut.first(where: !\.isClearToFly)?.name, "Noah") 125 | } 126 | 127 | func test_contains_true() { 128 | XCTAssertTrue(sut.contains(where: \.weight < 85)) 129 | } 130 | 131 | func test_contains_false() { 132 | XCTAssertFalse(sut.contains(where: \.weight > 185)) 133 | } 134 | 135 | func test_allSatisfy_true() { 136 | XCTAssertTrue(sut.allSatisfy(\.age > 20)) 137 | } 138 | 139 | func test_allSatisfy_false() { 140 | XCTAssertFalse(sut.allSatisfy(\.age > 35)) 141 | } 142 | 143 | } 144 | --------------------------------------------------------------------------------