Skip to content

Instantly share code, notes, and snippets.

@lmas
Created April 7, 2021 13:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lmas/5a08f6f2f0a21b2f3ae99c1b42a47cee to your computer and use it in GitHub Desktop.
Save lmas/5a08f6f2f0a21b2f3ae99c1b42a47cee to your computer and use it in GitHub Desktop.
Calculate the average time to read a text
// Copyright © 2021 Alex
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
package internal
import (
"time"
"unicode"
)
// https://en.wikipedia.org/wiki/Words_per_minute
// Reading seems to average around 200 +- 50 words/minute for english, according to various web sources.
const avgWordsPerMin float64 = 200
func timeToRead(src []byte) time.Duration {
words := countWords(src)
wpm := float64(words) / avgWordsPerMin
dur := time.Duration(wpm*60) * time.Second // We want the minimal unit of time to be seconds (roughly)
return dur
}
func countWords(b []byte) int {
words, inWord := 0, false
for _, r := range b {
if unicode.IsSpace(rune(r)) {
inWord = false
} else if inWord == false {
inWord = true
words++
}
}
return words
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment