Added dict with additional cards

This commit is contained in:
Artyom Belousov 2021-02-03 19:09:08 +03:00
parent 181f3bc0aa
commit 88ea431a27
26 changed files with 232 additions and 35 deletions

View file

@ -0,0 +1,23 @@
package dicttranslate
import (
"encoding/json"
"io"
"io/ioutil"
)
func find(query string, dict map[string]string, maxDist int) (string, bool) {
var keys []string
for i := range dict {
keys = append(keys, i)
}
key, f := match(query, keys, maxDist)
return dict[key], f
}
func FindFromReader(query string, reader io.Reader, maxDist int) (string, bool) {
content, _ := ioutil.ReadAll(reader)
dict := map[string]string{}
_ = json.Unmarshal(content, &dict)
return find(query, dict, maxDist)
}

View file

@ -0,0 +1,33 @@
package dicttranslate
import (
"github.com/stretchr/testify/assert"
"strings"
"testing"
)
func TestFindEmpty(t *testing.T) {
dict := map[string]string{}
_, f := find("", dict, 0)
assert.False(t, f)
}
func TestFindEntry(t *testing.T) {
dict := map[string]string{
"entry": "value",
}
val, f := find("entry", dict, 0)
assert.True(t, f)
assert.Equal(t, "value", val)
}
func TestFindFromReaderFail(t *testing.T) {
_, f := FindFromReader("entry", strings.NewReader("{}"), 0)
assert.False(t, f)
}
func TestFindFromReaderSuccess(t *testing.T) {
value, f := FindFromReader("entry", strings.NewReader("{\"entry\":\"value\"}"), 0)
assert.True(t, f)
assert.Equal(t, "value", value)
}

View file

@ -0,0 +1,21 @@
package dicttranslate
import "github.com/texttheater/golang-levenshtein/levenshtein"
func match(query string, opts []string, maxDist int) (string, bool) {
bestInd := -1
bestDist := 0
for i, s := range opts {
cfg := levenshtein.DefaultOptions
cfg.SubCost = 1
dist := levenshtein.DistanceForStrings([]rune(s), []rune(query), cfg)
if dist <= maxDist && (bestInd == -1 || dist < bestDist) {
bestInd = i
bestDist = dist
}
}
if bestInd == -1 {
return "", false
}
return opts[bestInd], true
}

View file

@ -0,0 +1,52 @@
package dicttranslate
import (
"github.com/stretchr/testify/assert"
"testing"
)
func TestMatch(t *testing.T) {
type testCase struct {
name string
query string
opts []string
shouldFind bool
match string
}
tests := []testCase{
{
name: "No options",
query: "opt",
opts: []string{},
shouldFind: false,
},
{
name: "Match one",
query: "option",
opts: []string{"opt1on"},
shouldFind: true,
match: "opt1on",
},
{
name: "Match exact",
query: "opt1on",
opts: []string{"option", "opt1on"},
shouldFind: true,
match: "opt1on",
},
{
name: "Do not match bad options",
query: "random",
opts: []string{"option", "opt1on"},
shouldFind: false,
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
val, f := match(test.query, test.opts, 1)
assert.Equal(t, test.shouldFind, f)
assert.Equal(t, test.match, val)
})
}
}