From 182532036904ee50f83c5df78c885f8ad47feb7e Mon Sep 17 00:00:00 2001 From: Julien Voisin Date: Fri, 18 Jul 2025 05:53:41 +0200 Subject: [PATCH] refactor(template): remove unused functions and reduce the complexity of `truncate` function - Remove unused functions like hasKey, domain, hasPrefix and contains. - Lower the complexity of truncate from O(n) to O(1). --- internal/template/functions.go | 20 +++----------------- internal/template/functions_test.go | 12 ------------ 2 files changed, 3 insertions(+), 29 deletions(-) diff --git a/internal/template/functions.go b/internal/template/functions.go index c1215e63..fe06f247 100644 --- a/internal/template/functions.go +++ b/internal/template/functions.go @@ -34,7 +34,6 @@ func (f *funcMap) Map() template.FuncMap { return template.FuncMap{ "formatFileSize": formatFileSize, "dict": dict, - "hasKey": hasKey, "truncate": truncate, "isEmail": isEmail, "baseURL": config.Opts.BaseURL, @@ -77,9 +76,7 @@ func (f *funcMap) Map() template.FuncMap { "mustBeProxyfied": func(mediaType string) bool { return slices.Contains(config.Opts.MediaProxyResourceTypes(), mediaType) }, - "domain": urllib.Domain, - "hasPrefix": strings.HasPrefix, - "contains": strings.Contains, + "domain": urllib.Domain, "replace": func(str, old, new string) string { return strings.Replace(str, old, new, 1) }, @@ -132,20 +129,9 @@ func dict(values ...interface{}) (map[string]interface{}, error) { return dict, nil } -func hasKey(dict map[string]string, key string) bool { - if value, found := dict[key]; found { - return value != "" - } - return false -} - func truncate(str string, max int) string { - runes := 0 - for i := range str { - runes++ - if runes > max { - return str[:i] + "…" - } + if runes := []rune(str); len(runes) > max { + return string(runes[:max]) + "…" } return str } diff --git a/internal/template/functions_test.go b/internal/template/functions_test.go index ddd18a60..dd71f28f 100644 --- a/internal/template/functions_test.go +++ b/internal/template/functions_test.go @@ -43,18 +43,6 @@ func TestDictWithInvalidMap(t *testing.T) { } } -func TestHasKey(t *testing.T) { - input := map[string]string{"k": "v"} - - if !hasKey(input, "k") { - t.Fatal(`This key exists in the map and should returns true`) - } - - if hasKey(input, "missing") { - t.Fatal(`This key doesn't exists in the given map and should returns false`) - } -} - func TestTruncateWithShortTexts(t *testing.T) { scenarios := []string{"Short text", "Короткий текст"}