Browse Source

Added test case and improved encodeWord

Piotr Czajkowski 3 years ago
parent
commit
b3b97dd217
2 changed files with 29 additions and 12 deletions
  1. 7 0
      app.go
  2. 22 12
      app_test.go

+ 7 - 0
app.go

@@ -12,11 +12,18 @@ func encodeWord(word []rune, wordLength int) {
 		return
 	}
 
+	original := string(word)
 	toShuffle := word[1 : wordLength-1]
 	toShuffleLength := wordLength - 2
 	rand.Shuffle(toShuffleLength, func(i, j int) {
 		toShuffle[i], toShuffle[j] = toShuffle[j], toShuffle[i]
 	})
+
+	if string(word) == original {
+		rand.Shuffle(toShuffleLength, func(i, j int) {
+			toShuffle[i], toShuffle[j] = toShuffle[j], toShuffle[i]
+		})
+	}
 }
 
 //EncodeText returns encoded provided text and sorted array of encoded words

+ 22 - 12
app_test.go

@@ -4,21 +4,31 @@ import (
 	"testing"
 )
 
-func TestDecodeEncode(t *testing.T) {
-	text := `This is a long looong test sentence,
-with some big (biiiiig) words!`
+type testCase struct {
+	text  string
+	count int
+}
 
-	encodedText, encodedWords := EncodeText([]rune(text))
-	if encodedText == text {
-		t.Errorf("Encoded text '%s' should be different than provided text '%s'!", encodedText, text)
+func TestDecodeEncode(t *testing.T) {
+	testCases := []testCase{
+		{"This is a long looong test sentence,\nwith some big (biiiiig) words!", 8},
+		{"Pre-translation generally means applying the TM(s) to one or more files as whole instead of moving segment by segment.", 11},
 	}
 
-	if len(encodedWords) != 8 {
-		t.Errorf("There should be 8 encoded words! %v", encodedWords)
-	}
+	for _, item := range testCases {
+		encodedText, encodedWords := EncodeText([]rune(item.text))
+		if encodedText == item.text {
+			t.Errorf("Encoded text '%s' should be different than provided text '%s'!", encodedText, item.text)
+		}
+
+		count := len(encodedWords)
+		if count != item.count {
+			t.Errorf("There should be %d encoded words instead of %d! %v", item.count, count, encodedWords)
+		}
 
-	decodedText := DecodeText([]rune(encodedText), encodedWords)
-	if decodedText != text {
-		t.Errorf("Decoded text '%s' should be same as provided text '%s'!", decodedText, text)
+		decodedText := DecodeText([]rune(encodedText), encodedWords)
+		if decodedText != item.text {
+			t.Errorf("Decoded text '%s' should be same as provided text '%s'!", decodedText, item.text)
+		}
 	}
 }