From b6d3b703c9c05e30ecf61c37c920951174677971 Mon Sep 17 00:00:00 2001 From: ElnuDev Date: Fri, 21 Jul 2023 12:17:54 -0700 Subject: [PATCH] Add result truncation --- dict/main.go | 14 +++++++++++--- dict/templates/search.html | 2 +- 2 files changed, 12 insertions(+), 4 deletions(-) diff --git a/dict/main.go b/dict/main.go index c2e5dde..c240895 100644 --- a/dict/main.go +++ b/dict/main.go @@ -69,10 +69,11 @@ func ParseEntry(entry jmdict.JmdictEntry) Entry { } } -func Search(query string) (exactResults []Entry, otherResults []Entry) { +func Search(query string) (exactResults []Entry, otherResults []Entry, truncated bool) { query = strings.TrimSpace(query) exactResults = make([]Entry, 0) otherResults = make([]Entry, 0) + count := 0 for _, jmdictEntry := range dict.Entries { exactMatch := false for _, kanji := range jmdictEntry.Kanji { @@ -98,6 +99,11 @@ func Search(query string) (exactResults []Entry, otherResults []Entry) { } else { otherResults = append(otherResults, entry) } + count++ + if count >= 500 { + truncated = true + break + } } return } @@ -105,13 +111,15 @@ func Search(query string) (exactResults []Entry, otherResults []Entry) { type searchTemplateData struct { ExactResults []Entry OtherResults []Entry + Truncated bool Count int } -func initSearchTemplateData(exactResults []Entry, otherResults []Entry) searchTemplateData { +func initSearchTemplateData(exactResults []Entry, otherResults []Entry, truncated bool) searchTemplateData { return searchTemplateData{ ExactResults: exactResults, OtherResults: otherResults, + Truncated: truncated, Count: len(exactResults) + len(otherResults), } } @@ -156,7 +164,7 @@ func main() { w.Header().Set("Content-Type", "application/json; charset=utf-8") r.ParseMultipartForm(0) query := r.FormValue("q") - exactResults, otherResults := Search(query) + exactResults, otherResults, _ := Search(query) jsonBytes, _ := json.Marshal(append(exactResults, otherResults...)) fmt.Fprint(w, string(jsonBytes)) return false diff --git a/dict/templates/search.html b/dict/templates/search.html index 0e077d4..90053b1 100644 --- a/dict/templates/search.html +++ b/dict/templates/search.html @@ -1,5 +1,5 @@ {{- define "search" -}} -

{{ if eq .Count 0 }}No results{{ else }}{{ .Count }} result{{ if ne .Count 1}}s{{ end }}{{ end }}.

+

{{ if .Truncated }}Truncated results, showing first {{ .Count }}{{ else }}{{ if eq .Count 0 }}No results{{ else }}{{ .Count }} result{{ if ne .Count 1}}s{{ end }}{{ end }}{{ end }}.

{{- range .ExactResults -}} {{- template "word" . -}} {{- end }}