Skip to content

Commit 0158c97

Browse files
authored
Prefer earlier match with same score for input search. (#186)
1 parent da2b7e2 commit 0158c97

2 files changed

Lines changed: 33 additions & 1 deletion

File tree

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
## Changes
99

1010
- Log to stderr instead of stdout.
11+
- Prefer earlier match with same score for input search.
1112

1213
## Fixes
1314

‎src/state/filtered_lines.rs‎

Lines changed: 32 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,13 +8,19 @@ pub type ContinuousMatch<'a> = sublime_fuzzy::ContinuousMatches<'a>;
88

99
pub struct FilteredLines(Either<Vec<(usize, Match)>, usize>);
1010

11+
fn order_items(m1: &Match, m2: &Match) -> std::cmp::Ordering {
12+
m2.score()
13+
.cmp(&m1.score())
14+
.then_with(|| m1.matched_indices().cmp(m2.matched_indices()))
15+
}
16+
1117
impl FilteredLines {
1218
pub fn searched<'a>(entries: impl Iterator<Item = &'a str>, search_string: &str) -> Self {
1319
let mut v = entries
1420
.enumerate()
1521
.filter_map(|(i, e)| Some((i, sublime_fuzzy::best_match(search_string, e)?)))
1622
.collect::<Vec<_>>();
17-
v.sort_by_key(|(_, m)| std::cmp::Reverse(m.score()));
23+
v.sort_by(|(_, m1), (_, m2)| order_items(m1, m2));
1824
Self(Either::Left(v))
1925
}
2026

@@ -75,3 +81,28 @@ impl FilteredLines {
7581
.into_iter()
7682
}
7783
}
84+
85+
#[cfg(test)]
86+
mod tests {
87+
use itertools::Itertools;
88+
use test_case::test_case;
89+
90+
use super::*;
91+
92+
#[test_case(vec!["asd"], "asd", vec!["asd"])]
93+
#[test_case(vec!["xy", "yx"], "xy", vec!["xy"])]
94+
#[test_case(vec!["xy", "yx"], "x", vec!["xy", "yx"])]
95+
#[test_case(vec!["xy", "yx"], "y", vec!["yx", "xy"])]
96+
#[test_case(vec!["ab-cd", "ac-bd"], "cd", vec!["ab-cd", "ac-bd"])]
97+
#[test_case(vec!["ab-cd", "cd-ab"], "ab", vec!["ab-cd", "cd-ab"])]
98+
fn test_order_items(input: Vec<&str>, query: &str, expected: Vec<&str>) {
99+
let result = input
100+
.into_iter()
101+
.filter_map(|x| Some(dbg!(x, sublime_fuzzy::best_match(query, x)?)))
102+
.sorted_by(|(_, m1), (_, m2)| order_items(m1, m2))
103+
.map(|(x, _)| (x))
104+
.collect::<Vec<_>>();
105+
106+
assert_eq!(result, expected)
107+
}
108+
}

0 commit comments

Comments
 (0)