github.com/tencent/goom@v1.0.1/internal/unexports/suggestion.go (about)

     1  package unexports
     2  
     3  import (
     4  	"strings"
     5  )
     6  
     7  // suggester 模糊匹配智能提示器
     8  type suggester struct {
     9  	key                                   string
    10  	a, b                                  int
    11  	suggestionA, suggestionB, suggestionC string
    12  }
    13  
    14  // newSuggester 创建提示器
    15  func newSuggester(key string) *suggester {
    16  	return &suggester{key: key}
    17  }
    18  
    19  // AddItem 添加匹配条目
    20  func (s *suggester) AddItem(item string) {
    21  	if fuzzyMatch(item, s.key, "/") {
    22  		if s.b%3 == 0 {
    23  			s.suggestionA = item
    24  		} else if s.b%3 == 1 {
    25  			s.suggestionB = item
    26  		} else {
    27  			s.suggestionC = item
    28  		}
    29  		s.b++
    30  	} else if fuzzyMatch(item, s.key, ".") {
    31  		if s.a%2 == 0 {
    32  			s.suggestionB = item
    33  		} else {
    34  			s.suggestionC = item
    35  		}
    36  		s.a++
    37  	}
    38  }
    39  
    40  // fuzzyMatch 模糊匹配,用于提供 suggestion
    41  func fuzzyMatch(target, source, token string) bool {
    42  	if len(target) == 0 || len(source) == 0 || len(token) == 0 {
    43  		return false
    44  	}
    45  	keywords := strings.Split(source, token)
    46  	keyword := keywords[len(keywords)-1]
    47  	return strings.Contains(target, keyword)
    48  }
    49  
    50  // Suggestions 获取提示内容
    51  func (s *suggester) Suggestions() []string {
    52  	return []string{s.suggestionA, s.suggestionB, s.suggestionC}
    53  }