| 1 | pub fn score(query: &str, candidate: &str) -> Option<i64> { |
| 2 | let query: Vec<char> = query |
| 3 | .to_lowercase() |
| 4 | .chars() |
| 5 | .filter(|c| !c.is_whitespace()) |
| 6 | .collect(); |
| 7 | if query.is_empty() { |
| 8 | return Some(0); |
| 9 | } |
| 10 | let lowered: Vec<char> = candidate.to_lowercase().chars().collect(); |
| 11 | let plain = score_plain(&query, &lowered, false); |
| 12 | let word_starts = score_plain(&query, &lowered, true); |
| 13 | plain.max(word_starts) |
| 14 | } |
| 15 | |
| 16 | fn is_word_start(candidate: &[char], index: usize) -> bool { |
| 17 | index == 0 || !candidate[index - 1].is_alphanumeric() |
| 18 | } |
| 19 | |
| 20 | fn score_plain(query: &[char], candidate: &[char], prefer_word_starts: bool) -> Option<i64> { |
| 21 | let mut score = 0i64; |
| 22 | let mut position = 0usize; |
| 23 | let mut previous_match: Option<usize> = None; |
| 24 | for &wanted in query { |
| 25 | let mut occurrences = |
| 26 | (position..candidate.len()).filter(|&index| candidate[index] == wanted); |
| 27 | let found = if prefer_word_starts { |
| 28 | (position..candidate.len()) |
| 29 | .find(|&index| candidate[index] == wanted && is_word_start(candidate, index)) |
| 30 | .or_else(|| occurrences.next())? |
| 31 | } else { |
| 32 | occurrences.next()? |
| 33 | }; |
| 34 | score += 10; |
| 35 | if previous_match.is_some_and(|previous| previous + 1 == found) { |
| 36 | score += 15; |
| 37 | } |
| 38 | if is_word_start(candidate, found) { |
| 39 | score += 20; |
| 40 | } else { |
| 41 | score -= (found - previous_match.map_or(0, |previous| previous + 1)) as i64; |
| 42 | } |
| 43 | previous_match = Some(found); |
| 44 | position = found + 1; |
| 45 | } |
| 46 | Some(score) |
| 47 | } |
| 48 | |
| 49 | /// Without a query the items keep their order, so callers decide what comes first. |
| 50 | pub fn rank<T: Clone>(query: &str, items: &[(String, T)], limit: usize) -> Vec<T> { |
| 51 | if query.trim().is_empty() { |
| 52 | return items |
| 53 | .iter() |
| 54 | .take(limit) |
| 55 | .map(|(_, item)| item.clone()) |
| 56 | .collect(); |
| 57 | } |
| 58 | let mut scored: Vec<(i64, usize, usize)> = items |
| 59 | .iter() |
| 60 | .enumerate() |
| 61 | .filter_map(|(index, (label, _))| { |
| 62 | score(query, label).map(|score| (score, label.chars().count(), index)) |
| 63 | }) |
| 64 | .collect(); |
| 65 | scored.sort_by(|left, right| { |
| 66 | right |
| 67 | .0 |
| 68 | .cmp(&left.0) |
| 69 | .then(left.1.cmp(&right.1)) |
| 70 | .then(left.2.cmp(&right.2)) |
| 71 | }); |
| 72 | scored |
| 73 | .into_iter() |
| 74 | .take(limit) |
| 75 | .map(|(_, _, index)| items[index].1.clone()) |
| 76 | .collect() |
| 77 | } |
| 78 | |
| 79 | #[cfg(test)] |
| 80 | mod tests { |
| 81 | use super::*; |
| 82 | |
| 83 | #[test] |
| 84 | fn an_empty_query_keeps_the_given_order() { |
| 85 | let items = vec![ |
| 86 | ("Longer recent chat".to_owned(), 1), |
| 87 | ("?".to_owned(), 2), |
| 88 | ("fme".to_owned(), 3), |
| 89 | ]; |
| 90 | assert_eq!(rank("", &items, 2), [1, 2]); |
| 91 | assert_eq!(rank(" ", &items, 5), [1, 2, 3]); |
| 92 | } |
| 93 | |
| 94 | #[test] |
| 95 | fn subsequence_matches_and_misses() { |
| 96 | assert!(score("pgr", "Project Green").is_some()); |
| 97 | assert!(score("xyz", "Project Green").is_none()); |
| 98 | assert_eq!(score("", "anything"), Some(0)); |
| 99 | } |
| 100 | |
| 101 | #[test] |
| 102 | fn contiguous_word_start_beats_scattered() { |
| 103 | let tight = score("proj", "Project Green").unwrap(); |
| 104 | let scattered = score("proj", "Pxxrxxoxxj").unwrap(); |
| 105 | assert!(tight > scattered); |
| 106 | } |
| 107 | |
| 108 | #[test] |
| 109 | fn rank_orders_by_score_and_limits() { |
| 110 | let items = vec![ |
| 111 | ("Alpha Team".to_owned(), 1), |
| 112 | ("Beta".to_owned(), 2), |
| 113 | ("Alphabet".to_owned(), 3), |
| 114 | ]; |
| 115 | let ranked = rank("alph", &items, 5); |
| 116 | assert_eq!(ranked.len(), 2); |
| 117 | assert_eq!(rank("a", &items, 1).len(), 1); |
| 118 | } |
| 119 | |
| 120 | #[test] |
| 121 | fn initials_beat_a_contiguous_match_inside_a_word() { |
| 122 | let items = vec![ |
| 123 | ("QA cw review".to_owned(), "meeting"), |
| 124 | ("Ada Lovelace, Christoph Wiechert".to_owned(), "group"), |
| 125 | ("Christoph Wiechert".to_owned(), "person"), |
| 126 | ]; |
| 127 | assert_eq!(rank("cw", &items, 3), ["person", "group", "meeting"]); |
| 128 | } |
| 129 | |
| 130 | #[test] |
| 131 | fn case_is_ignored() { |
| 132 | assert!(score("ALPHA", "alpha").is_some()); |
| 133 | } |
| 134 | } |