From 17d372677d08cf2a9a4c0f83807f20fcfb182de7 Mon Sep 17 00:00:00 2001 From: Martin Atkins Date: Sat, 20 May 2017 09:45:15 -0700 Subject: [PATCH] json: Generalize "keywordSuggestion" for general name suggestions keywordSuggestion is now a wrapper around nameSuggestion with a predefined list of names. --- zcl/json/didyoumean.go | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/zcl/json/didyoumean.go b/zcl/json/didyoumean.go index 1016026..fbdd8bf 100644 --- a/zcl/json/didyoumean.go +++ b/zcl/json/didyoumean.go @@ -10,10 +10,23 @@ var keywords = []string{"false", "true", "null"} // given string and returns it if found. If no keyword is close enough, returns // the empty string. func keywordSuggestion(given string) string { - for _, kw := range keywords { - dist := levenshtein.Distance(given, kw, nil) + return nameSuggestion(given, keywords) +} + +// nameSuggestion tries to find a name from the given slice of suggested names +// that is close to the given name and returns it if found. If no suggestion +// is close enough, returns the empty string. +// +// The suggestions are tried in order, so earlier suggestions take precedence +// if the given string is similar to two or more suggestions. +// +// This function is intended to be used with a relatively-small number of +// suggestions. It's not optimized for hundreds or thousands of them. +func nameSuggestion(given string, suggestions []string) string { + for _, suggestion := range suggestions { + dist := levenshtein.Distance(given, suggestion, nil) if dist < 3 { // threshold determined experimentally - return kw + return suggestion } } return ""