From 70476bea9a8db3546b548e2cdfaa7d0ff816daf2 Mon Sep 17 00:00:00 2001 From: Greg Shuflin Date: Fri, 27 Sep 2024 15:10:10 -0700 Subject: [PATCH] De-duplicate suggestion methods (#2392) --- src/justfile.rs | 72 ++++++++++++++++++++----------------------------- 1 file changed, 29 insertions(+), 43 deletions(-) diff --git a/src/justfile.rs b/src/justfile.rs index 1a4043ff5e..5123f8c73d 100644 --- a/src/justfile.rs +++ b/src/justfile.rs @@ -34,53 +34,39 @@ pub(crate) struct Justfile<'src> { } impl<'src> Justfile<'src> { - pub(crate) fn suggest_recipe(&self, input: &str) -> Option> { - let mut suggestions = self - .recipes - .keys() - .map(|name| { - ( - edit_distance(name, input), - Suggestion { name, target: None }, - ) - }) - .chain(self.aliases.iter().map(|(name, alias)| { - ( - edit_distance(name, input), - Suggestion { - name, - target: Some(alias.target.name.lexeme()), - }, - ) - })) - .filter(|(distance, _suggestion)| distance < &3) - .collect::>(); - suggestions.sort_by_key(|(distance, _suggestion)| *distance); - - suggestions - .into_iter() + fn find_suggestion( + input: &str, + candidates: impl Iterator>, + ) -> Option> { + candidates + .map(|suggestion| (edit_distance(input, suggestion.name), suggestion)) + .filter(|(distance, _suggestion)| *distance < 3) + .min_by_key(|(distance, _suggestion)| *distance) .map(|(_distance, suggestion)| suggestion) - .next() } - pub(crate) fn suggest_variable(&self, input: &str) -> Option> { - let mut suggestions = self - .assignments - .keys() - .map(|name| { - ( - edit_distance(name, input), - Suggestion { name, target: None }, - ) - }) - .filter(|(distance, _suggestion)| distance < &3) - .collect::>(); - suggestions.sort_by_key(|(distance, _suggestion)| *distance); + pub(crate) fn suggest_recipe(&self, input: &str) -> Option> { + Self::find_suggestion( + input, + self + .recipes + .keys() + .map(|name| Suggestion { name, target: None }) + .chain(self.aliases.iter().map(|(name, alias)| Suggestion { + name, + target: Some(alias.target.name.lexeme()), + })), + ) + } - suggestions - .into_iter() - .map(|(_distance, suggestion)| suggestion) - .next() + pub(crate) fn suggest_variable(&self, input: &str) -> Option> { + Self::find_suggestion( + input, + self + .assignments + .keys() + .map(|name| Suggestion { name, target: None }), + ) } pub(crate) fn run(