| 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 | score_plain(&query, &lowered) |
| 12 | } |
| 13 | |
| 14 | fn score_plain(query: &[char], candidate: &[char]) -> Option<i64> { |
| 15 | let mut score = 0i64; |
| 16 | let mut position = 0usize; |
| 17 | let mut previous_match: Option<usize> = None; |
| 18 | for &wanted in query { |
| 19 | let found = candidate[position..].iter().position(|&c| c == wanted)? + position; |
| 20 | score += 10; |
| 21 | if previous_match.is_some_and(|previous| previous + 1 == found) { |
| 22 | score += 15; |
| 23 | } |
| 24 | if found == 0 || !candidate[found - 1].is_alphanumeric() { |
| 25 | score += 20; |
| 26 | } |
| 27 | score -= (found - previous_match.map_or(0, |previous| previous + 1)) as i64; |
| 28 | previous_match = Some(found); |
| 29 | position = found + 1; |
| 30 | } |
| 31 | Some(score) |
| 32 | } |
| 33 | |
| 34 | pub fn rank<T: Clone>(query: &str, items: &[(String, T)], limit: usize) -> Vec<T> { |
| 35 | let mut scored: Vec<(i64, usize)> = items |
| 36 | .iter() |
| 37 | .enumerate() |
| 38 | .filter_map(|(index, (label, _))| score(query, label).map(|score| (score, index))) |
| 39 | .collect(); |
| 40 | scored.sort_by(|left, right| right.0.cmp(&left.0).then(left.1.cmp(&right.1))); |
| 41 | scored |
| 42 | .into_iter() |
| 43 | .take(limit) |
| 44 | .map(|(_, index)| items[index].1.clone()) |
| 45 | .collect() |
| 46 | } |
| 47 | |
| 48 | #[cfg(test)] |
| 49 | mod tests { |
| 50 | use super::*; |
| 51 | |
| 52 | #[test] |
| 53 | fn subsequence_matches_and_misses() { |
| 54 | assert!(score("pgr", "Project Green").is_some()); |
| 55 | assert!(score("xyz", "Project Green").is_none()); |
| 56 | assert_eq!(score("", "anything"), Some(0)); |
| 57 | } |
| 58 | |
| 59 | #[test] |
| 60 | fn contiguous_word_start_beats_scattered() { |
| 61 | let tight = score("proj", "Project Green").unwrap(); |
| 62 | let scattered = score("proj", "Pxxrxxoxxj").unwrap(); |
| 63 | assert!(tight > scattered); |
| 64 | } |
| 65 | |
| 66 | #[test] |
| 67 | fn rank_orders_by_score_and_limits() { |
| 68 | let items = vec![ |
| 69 | ("Alpha Team".to_owned(), 1), |
| 70 | ("Beta".to_owned(), 2), |
| 71 | ("Alphabet".to_owned(), 3), |
| 72 | ]; |
| 73 | let ranked = rank("alph", &items, 5); |
| 74 | assert_eq!(ranked.len(), 2); |
| 75 | assert_eq!(rank("a", &items, 1).len(), 1); |
| 76 | } |
| 77 | |
| 78 | #[test] |
| 79 | fn case_is_ignored() { |
| 80 | assert!(score("ALPHA", "alpha").is_some()); |
| 81 | } |
| 82 | } |