Merge pull request #3 from sundowndev/feat/sortQueryResults

Sort query results by score
master
Raphaël 2020-04-14 12:27:39 +01:00 committed by GitHub
commit 0a172c9d11
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 78 additions and 4 deletions

View File

@ -41,6 +41,7 @@ var queryCmd = &cobra.Command{
for _, file := range files {
score := client.GetWordScoreFromFile(file, word)
// If score is 0 then ignore it
if score == 0 {
continue
}
@ -54,11 +55,11 @@ var queryCmd = &cobra.Command{
queryResults = append(queryResults, &engine.QueryResult{
File: file,
Count: score,
Score: score,
FirstMatch: engine.GetFirstMatchingLine(text, word),
})
}
engine.ShowResults(queryResults)
engine.ShowResults(engine.SortResultsByScore(queryResults))
},
}

View File

@ -3,6 +3,7 @@ package engine
import (
"fmt"
"os"
"sort"
"text/tabwriter"
)
@ -12,7 +13,7 @@ const tabPaddingChar = ' '
// QueryResult defines the structure of a query result
type QueryResult struct {
File string
Count float64
Score float64
FirstMatch string
}
@ -23,6 +24,15 @@ func ShowResults(results []*QueryResult) {
fmt.Fprintln(w, "File\tCount\tFirst match\t")
for _, v := range results {
fmt.Fprintf(w, "%v\t%v\t%v\t\n", v.File, v.Count, v.FirstMatch)
fmt.Fprintf(w, "%v\t%v\t%v\t\n", v.File, v.Score, v.FirstMatch)
}
}
// SortResultsByScore sort the given array of results by their score.
func SortResultsByScore(results []*QueryResult) []*QueryResult {
sort.Slice(results, func(i, j int) bool {
return results[i].Score > results[j].Score
})
return results
}

63
engine/results_test.go Normal file
View File

@ -0,0 +1,63 @@
package engine
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestResults(t *testing.T) {
assert := assert.New(t)
t.Run("SortResultsByScore", func(t *testing.T) {
results := []*QueryResult{
&QueryResult{
File: "/file",
Score: 1,
FirstMatch: "",
},
&QueryResult{
File: "/file",
Score: 3,
FirstMatch: "",
},
&QueryResult{
File: "/file",
Score: 9,
FirstMatch: "",
},
&QueryResult{
File: "/file",
Score: 2,
FirstMatch: "",
},
}
expected := []*QueryResult{
&QueryResult{
File: "/file",
Score: 9,
FirstMatch: "",
},
&QueryResult{
File: "/file",
Score: 3,
FirstMatch: "",
},
&QueryResult{
File: "/file",
Score: 2,
FirstMatch: "",
},
&QueryResult{
File: "/file",
Score: 1,
FirstMatch: "",
},
}
sorted := SortResultsByScore(results)
assert.Equal(expected, sorted, "should be equal")
})
}