|
1 | | -use std::path::{Path, PathBuf}; |
2 | | - |
3 | 1 | use regex::Regex; |
| 2 | +use std::path::{Path, PathBuf}; |
| 3 | +use strsim::jaro_winkler; |
4 | 4 |
|
5 | 5 | pub(crate) fn build_regex_search_input( |
6 | 6 | search_input: Option<&str>, |
@@ -40,3 +40,49 @@ pub(crate) fn replace_tilde_with_home_dir(path: impl AsRef<Path>) -> PathBuf { |
40 | 40 | } |
41 | 41 | path.to_path_buf() |
42 | 42 | } |
| 43 | + |
| 44 | +fn file_name_from_path(path: &str) -> String { |
| 45 | + let path = Path::new(path); |
| 46 | + let file_name = path.file_name().unwrap().to_str().unwrap(); |
| 47 | + return file_name.to_string(); |
| 48 | +} |
| 49 | + |
| 50 | +/// This function can be used to sort the given vector on basis of similarity between the input & the vector |
| 51 | +/// |
| 52 | +/// ### Arguments |
| 53 | +/// * `&mut vector` - it needs a mutable reference to the vector |
| 54 | +/// ### Examples |
| 55 | +/// ```rust |
| 56 | +/// use rust_search::{SearchBuilder, similarity_sort}; |
| 57 | +/// fn main() { |
| 58 | +/// let search_input = "fly"; |
| 59 | +/// let mut search: Vec<String> = SearchBuilder::default() |
| 60 | +/// .location("~/Desktop/") |
| 61 | +/// .search_input(search_input) |
| 62 | +/// .depth(1) |
| 63 | +/// .ignore_case() |
| 64 | +/// .build() |
| 65 | +/// .collect(); |
| 66 | +
|
| 67 | +/// similarity_sort(&mut search, &search_input); |
| 68 | +/// for path in search { |
| 69 | +/// println!("{:?}", path); |
| 70 | +/// } |
| 71 | +/// } |
| 72 | +/// ``` |
| 73 | +/// |
| 74 | +/// search **without** similarity sort |
| 75 | +/// `["afly.txt", "bfly.txt", "flyer.txt", "fly.txt"]` |
| 76 | +/// |
| 77 | +/// search **with** similarity sort |
| 78 | +/// `["fly.txt", "flyer.txt", "afly.txt", "bfly.txt",]` |
| 79 | +pub fn similarity_sort(vector: &mut Vec<String>, input: &str) { |
| 80 | + vector.sort_by(|a, b| { |
| 81 | + let input = input.to_lowercase(); |
| 82 | + let a = file_name_from_path(a).to_lowercase(); |
| 83 | + let b = file_name_from_path(b).to_lowercase(); |
| 84 | + let a = jaro_winkler(a.as_str(), input.as_str()); |
| 85 | + let b = jaro_winkler(b.as_str(), input.as_str()); |
| 86 | + b.partial_cmp(&a).unwrap() |
| 87 | + }); |
| 88 | +} |
0 commit comments