From 9f22689cacd3569cf031aec7a8400d3efc522af6 Mon Sep 17 00:00:00 2001 From: Myzel394 Date: Sat, 29 Mar 2025 18:53:20 +0100 Subject: [PATCH] fix(server): Improvements --- server/common-documentation/mnt-apfs.go | 1 - server/common/levenshtein.go | 43 +++++++++++++++++++++++++ 2 files changed, 43 insertions(+), 1 deletion(-) create mode 100644 server/common/levenshtein.go diff --git a/server/common-documentation/mnt-apfs.go b/server/common-documentation/mnt-apfs.go index 864b400..0de42a3 100644 --- a/server/common-documentation/mnt-apfs.go +++ b/server/common-documentation/mnt-apfs.go @@ -73,4 +73,3 @@ var APFSDocumentationEnums = []docvalues.EnumString{ "This option indicates that in the course of the mount system call, the kernel should not follow any symlinks that may be present in the provided mount-on directory. This is the same as the -k option.", ), } - diff --git a/server/common/levenshtein.go b/server/common/levenshtein.go new file mode 100644 index 0000000..5544dee --- /dev/null +++ b/server/common/levenshtein.go @@ -0,0 +1,43 @@ +package common + +import ( + "github.com/hbollon/go-edlib" +) + +// Find items that are similar to the given input. +// This is used to find typos & suggest the correct item. +// Once an item is found that has a Damerau-Levenshtein distance of 1, it is immediately returned. +// If not, then the next 2 items of similarity 2, or 3 items of similarity 3 are returned. +// If no items with similarity <= 3 are found, then an empty slice is returned. +func FindSimilarItems[T ~string]( + input T, + items []T, +) []T { + itemsPerSimilarity := map[uint8][]T{ + 2: make([]T, 0, 2), + 3: make([]T, 0, 3), + } + + for _, item := range items { + similarity := edlib.DamerauLevenshteinDistance(string(item), string(input)) + + switch similarity { + case 1: + return []T{item} + case 2: + itemsPerSimilarity[2] = append(itemsPerSimilarity[2], item) + + if len(itemsPerSimilarity[2]) >= 2 { + return itemsPerSimilarity[2] + } + case 3: + itemsPerSimilarity[3] = append(itemsPerSimilarity[3], item) + + if len(itemsPerSimilarity[3]) >= 3 { + return itemsPerSimilarity[3] + } + } + } + + return append(itemsPerSimilarity[2], itemsPerSimilarity[3]...) +}