Procházet zdrojové kódy

refactor(readingtime): get rid of the obnoxious casts dance

jvoisin před 1 týdnem
rodič
revize
0976efd163

+ 2 - 3
internal/reader/readingtime/readingtime.go

@@ -5,7 +5,6 @@
 package readingtime
 package readingtime
 
 
 import (
 import (
-	"math"
 	"strings"
 	"strings"
 	"unicode"
 	"unicode"
 	"unicode/utf8"
 	"unicode/utf8"
@@ -19,9 +18,9 @@ func EstimateReadingTime(content string, defaultReadingSpeed, cjkReadingSpeed in
 	truncationPoint := min(len(sanitizedContent), 50)
 	truncationPoint := min(len(sanitizedContent), 50)
 
 
 	if isCJK(sanitizedContent[:truncationPoint]) {
 	if isCJK(sanitizedContent[:truncationPoint]) {
-		return int(math.Ceil(float64(utf8.RuneCountInString(sanitizedContent)) / float64(cjkReadingSpeed)))
+		return (utf8.RuneCountInString(sanitizedContent) + cjkReadingSpeed - 1) / cjkReadingSpeed
 	}
 	}
-	return int(math.Ceil(float64(countWords(sanitizedContent)) / float64(defaultReadingSpeed)))
+	return (countWords(sanitizedContent) + defaultReadingSpeed - 1) / defaultReadingSpeed
 }
 }
 
 
 func countWords(s string) int {
 func countWords(s string) int {

+ 18 - 1
internal/reader/readingtime/readingtime_test.go

@@ -3,7 +3,10 @@
 
 
 package readingtime
 package readingtime
 
 
-import "testing"
+import (
+	"strings"
+	"testing"
+)
 
 
 var samples = map[string]string{
 var samples = map[string]string{
 	"shortenglish": `This is a short paragraph in english, less than 250 chars.`,
 	"shortenglish": `This is a short paragraph in english, less than 250 chars.`,
@@ -79,6 +82,20 @@ func TestEstimateReadingTime(t *testing.T) {
 	}
 	}
 }
 }
 
 
+func TestEmptyEstimateReadingTime(t *testing.T) {
+	got := EstimateReadingTime("", 200, 500)
+	if got != 0 {
+		t.Errorf(`Wrong reading time, got %d instead of %d`, got, 0)
+	}
+}
+
+func TestRepeatedEstimateReadingTime(t *testing.T) {
+	got := EstimateReadingTime(strings.Repeat("word ", 200), 200, 500)
+	if got != 1 {
+		t.Errorf(`Wrong reading time, got %d instead of %d`, got, 1)
+	}
+}
+
 func BenchmarkEstimateReadingTime(b *testing.B) {
 func BenchmarkEstimateReadingTime(b *testing.B) {
 	for b.Loop() {
 	for b.Loop() {
 		for _, sample := range samples {
 		for _, sample := range samples {