Explorar el Código

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).
Julien Voisin hace 8 meses
padre
commit
1825320369
Se han modificado 2 ficheros con 3 adiciones y 29 borrados
  1. 3 17
      internal/template/functions.go
  2. 0 12
      internal/template/functions_test.go

+ 3 - 17
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
 }

+ 0 - 12
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", "Короткий текст"}