github.com/hashicorp/hcl/v2@v2.20.0/json/didyoumean.go (about)

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