Sources/OrgCore/Completion/FuzzyMatch.swift
26 lines · 1063 bytes
1import Foundation
2
3/// Subsequence matching for quick open: every query character must appear in order. Matches
4/// at word starts and runs of consecutive characters score higher; shorter names win ties.
5public enum FuzzyMatch {
6 /// What a match at a word start adds, before `score` scales it by 100.
7 public static let wordStartBonus = 8
8
9 public static func score(_ query: String, _ candidate: String) -> Int? {
10 let query = Array(query.lowercased().filter { !$0.isWhitespace })
11 let text = Array(candidate.lowercased())
12 guard !query.isEmpty else { return 0 }
13 var score = 0
14 var q = 0
15 var previousMatch = -2
16 for (i, c) in text.enumerated() where q < query.count && c == query[q] {
17 score += 1
18 if i == previousMatch + 1 { score += 5 }
19 if i == 0 || "/ -_.".contains(text[i - 1]) { score += wordStartBonus }
20 previousMatch = i
21 q += 1
22 }
23 guard q == query.count else { return nil }
24 return score * 100 - text.count
25 }
26}