closeMatches finds candidates that differ from name only in case, by a typo or two, or that contain it.
(name string, candidates []string, limit int)
| 628 | // closeMatches finds candidates that differ from name only in case, by a typo |
| 629 | // or two, or that contain it. |
| 630 | func closeMatches(name string, candidates []string, limit int) []string { |
| 631 | type match struct { |
| 632 | name string |
| 633 | rank int |
| 634 | } |
| 635 | lower := strings.ToLower(name) |
| 636 | var matches []match |
| 637 | for _, c := range candidates { |
| 638 | lc := strings.ToLower(c) |
| 639 | switch { |
| 640 | case lc == lower: |
| 641 | matches = append(matches, match{c, 0}) |
| 642 | case editDistance(lower, lc) <= 2: |
| 643 | matches = append(matches, match{c, 1}) |
| 644 | case len(lower) >= 3 && strings.Contains(lc, lower): |
| 645 | matches = append(matches, match{c, 2}) |
| 646 | } |
| 647 | } |
| 648 | sort.Slice(matches, func(i, j int) bool { |
| 649 | a, b := matches[i], matches[j] |
| 650 | if a.rank != b.rank { |
| 651 | return a.rank < b.rank |
| 652 | } |
| 653 | if len(a.name) != len(b.name) { |
| 654 | return len(a.name) < len(b.name) |
| 655 | } |
| 656 | return a.name < b.name |
| 657 | }) |
| 658 | var out []string |
| 659 | for i := 0; i < len(matches) && i < limit; i++ { |
| 660 | out = append(out, matches[i].name) |
| 661 | } |
| 662 | return out |
| 663 | } |
| 664 | |
| 665 | func editDistance(a, b string) int { |
| 666 | prev := make([]int, len(b)+1) |
no test coverage detected