github.com/hashicorp/hcl/v2@v2.20.0/didyoumean.go (about) 1 // Copyright (c) HashiCorp, Inc. 2 // SPDX-License-Identifier: MPL-2.0 3 4 package hcl 5 6 import ( 7 "github.com/agext/levenshtein" 8 ) 9 10 // nameSuggestion tries to find a name from the given slice of suggested names 11 // that is close to the given name and returns it if found. If no suggestion 12 // is close enough, returns the empty string. 13 // 14 // The suggestions are tried in order, so earlier suggestions take precedence 15 // if the given string is similar to two or more suggestions. 16 // 17 // This function is intended to be used with a relatively-small number of 18 // suggestions. It's not optimized for hundreds or thousands of them. 19 func nameSuggestion(given string, suggestions []string) string { 20 for _, suggestion := range suggestions { 21 dist := levenshtein.Distance(given, suggestion, nil) 22 if dist < 3 { // threshold determined experimentally 23 return suggestion 24 } 25 } 26 return "" 27 }