From 30f7ea8ddf1077ddc3bc289f56dff39c41258827 Mon Sep 17 00:00:00 2001 From: Andinus Date: Mon, 6 Apr 2020 23:52:41 +0530 Subject: Add Anagrams function --- search/anagrams.go | 35 +++++++++++++++++++++++++++++++++++ search/word.go | 8 +++----- 2 files changed, 38 insertions(+), 5 deletions(-) create mode 100644 search/anagrams.go diff --git a/search/anagrams.go b/search/anagrams.go new file mode 100644 index 0000000..e04dfd7 --- /dev/null +++ b/search/anagrams.go @@ -0,0 +1,35 @@ +package search + +import "tildegit.org/andinus/grus/storage" + +// Anagrams will search for unjumbled words in database, given sorted +// word along with all the anagrams. +func Anagrams(sorted string, db *storage.DB) (anagrams []string, err error) { + db.Mu.RLock() + defer db.Mu.RUnlock() + + stmt, err := db.Conn.Prepare("SELECT word FROM words WHERE sorted = ?") + if err != nil { + return + } + defer stmt.Close() + + rows, err := stmt.Query(sorted) + if err != nil { + return + } + defer rows.Close() + for rows.Next() { + var word string + err = rows.Scan(&word) + if err != nil { + return + } + anagrams = append(anagrams, word) + } + err = rows.Err() + if err != nil { + return + } + return +} diff --git a/search/word.go b/search/word.go index a62a393..c83c318 100644 --- a/search/word.go +++ b/search/word.go @@ -1,11 +1,9 @@ package search -import ( - "tildegit.org/andinus/grus/storage" -) +import "tildegit.org/andinus/grus/storage" // Word will search for unjumbled words in database, given sorted word. -func Word(sorted string, db *storage.DB) (out string, err error) { +func Word(sorted string, db *storage.DB) (word string, err error) { db.Mu.RLock() defer db.Mu.RUnlock() @@ -15,7 +13,7 @@ func Word(sorted string, db *storage.DB) (out string, err error) { } defer stmt.Close() - err = stmt.QueryRow(sorted).Scan(&out) + err = stmt.QueryRow(sorted).Scan(&word) if err != nil { return } -- cgit 1.4.1-2-gfad0