Browse Source

Initial import

master
maze 3 years ago
parent
commit
bef8821f8f
  1. 92
      readingtime.go
  2. 37
      readingtime_test.go

92
readingtime.go

@ -0,0 +1,92 @@
/*
Package readingtime estimates text reading times
We use non-scientific means of first establishing the number of words in a
given text and then based on read speeds from http://www.readingsoft.com/
calculate the time required to read that number of words in the text.
*/
package readingtime
import (
"regexp"
"strings"
"time"
)
// Reader profile average reading times in words per minute from http://www.readingsoft.com/
const (
InsufficientScreenReaderSpeed = 100.0
InsufficientPaperReaderSpeed = 110.0
AverageScreenReaderSpeed = 200.0
AveragePaperReaderSpeed = 240.0
FastScreenReaderSpeed = 300.0
FastPaperReaderSpeed = 400.0
AccomplishedScreenReaderSpeed = 700.0
AccomplishedPaperReaderSpeed = 1000.0
)
// Defaults.
var (
DefaultWordsPerMinute = AverageScreenReaderSpeed
DefaultWords = regexp.MustCompile(`\s`)
DefaultRound = time.Second
Default = Estimator{}
)
// Estimator can estimate the reading time.
type Estimator struct {
WordsPerMinute float64
// Words matcher.
Words *regexp.Regexp
// Round duration value, set to 1 to disable rounding.
Round time.Duration
// NoStrip skips trimming of white space characters.
NoStrip bool
}
// Estimate the reading time for a given text.
func (e Estimator) Estimate(text string) time.Duration {
if !e.NoStrip {
text = strings.TrimSpace(text)
}
if len(text) == 0 {
// Fast path
return 0
}
var (
wordsPerSecond float64
words int
)
if e.WordsPerMinute == 0 {
wordsPerSecond = DefaultWordsPerMinute / 60
} else {
wordsPerSecond = e.WordsPerMinute / 60
}
if e.Words == nil {
words = len(DefaultWords.Split(text, -1))
} else {
words = len(e.Words.Split(text, -1))
}
duration := time.Duration(float64(time.Second) * (float64(words) / wordsPerSecond))
if e.Round == 0 {
duration = (duration / DefaultRound) * DefaultRound
} else {
duration = (duration / e.Round) * e.Round
}
return duration
}
// Estimate the reading time for a given text using defaults.
func Estimate(text string) time.Duration {
return Default.Estimate(text)
}

37
readingtime_test.go

@ -0,0 +1,37 @@
package readingtime
import (
"fmt"
"strings"
"testing"
"time"
)
func TestEmpty(t *testing.T) {
if d := Estimate(""); d > 0 {
t.Fatalf("expected empty text to take no time, got %s", d)
}
if d := Estimate("\n\n\t "); d > 0 {
t.Fatalf("expected empty text to take no time, got %s", d)
}
}
var testCorpus = []struct {
Duration time.Duration
Text string
}{
{20 * time.Second, `Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum`},
{38 * time.Second, `Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?`},
{49 * time.Second, `But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?`},
}
func TestCorpus(t *testing.T) {
for _, test := range testCorpus {
t.Run(fmt.Sprintf("text-%d-words", len(strings.Split(test.Text, " "))), func(t *testing.T) {
if d := Estimate(test.Text); d != test.Duration {
t.Fatalf("expected %s, got %s", test.Duration, d)
}
})
}
}
Loading…
Cancel
Save