CutBox.app

Coverage Report

Created: 2024-03-12 03:40

.../Source/Extensions/Array+String+SwiftyStringScore.swift
Line
Count
Source
1
//
2
//  Array+String+SwiftyStringScore.swift
3
//  CutBox
4
//
5
//  Created by Jason Milkins on 3/4/18.
6
//  Copyright © 2018-2023 ocodo. All rights reserved.
7
//
8
9
import SwiftyStringScore
10
11
extension Array where Element == [String: String] {
12
13
2
    func fuzzySearchRankedFiltered(search: String, score: Double) -> [[String: String]] {
14
2
        return self
15
36
            .map { ($0, $0["string"]!.score(word: search)) }
16
36
            .filter { $0.1 > score }
17
12
            .sorted { $0.1 > $1.1 }
18
8
            .map { $0.0 }
19
2
    }
20
21
5
    func regexpSearchFiltered(search: String, options: NSRegularExpression.Options) -> [[String: String]] {
22
5
        // We need a *do* block because the incoming
23
5
        // search string might be an invalid regexp.
24
5
        // Return an empty array in that case.
25
5
        do {
26
5
            let regexp: NSRegularExpression =
27
5
            try NSRegularExpression(pattern: search,
28
5
                                    options: options)
29
5
            return self
30
72
                .filter {
31
72
                    let range = NSRange($0["string"]!.startIndex..., in: $0["string"]!)
32
72
                    return regexp.numberOfMatches(in: $0["string"]!, range: range) > 0
33
72
                }
34
5
        } catch {
35
1
            return []
36
18.4E
        }
37
18.4E
    }
38
39
5
    func substringSearchFiltered(search: String) -> [[String: String]] {
40
76
        self.filter { $0["string"]?.contains(search) ?? false }
41
5
    }
42
}
43
44
extension Array where Element == String {
45
46
4
    func fuzzySearchRankedFiltered(search: String, score: Double) -> [String] {
47
4
        return self
48
72
            .map { ($0, $0.score(word: search)) }
49
72
            .filter { $0.1 > score }
50
22
            .sorted { $0.1 > $1.1 }
51
15
            .map { $0.0 }
52
4
    }
53
54
7
    func regexpSearchFiltered(search: String, options: NSRegularExpression.Options) -> [String] {
55
7
        do {
56
7
            let regexp: NSRegularExpression =
57
7
            try NSRegularExpression(pattern: search,
58
7
                                    options: options)
59
7
            return self
60
94
                .filter {
61
94
                    let range = NSRange($0.startIndex..., in: $0)
62
94
                    return regexp.numberOfMatches(in: $0, range: range) > 0
63
94
                }
64
7
        } catch {
65
1
            return []
66
18.4E
        }
67
18.4E
    }
68
69
4
    func substringSearchFiltered(search: String) -> [String] {
70
56
        return self.filter {
71
56
            $0.contains(search)
72
56
        }
73
4
    }
74
}