Created
April 7, 2021 13:07
-
-
Save lmas/5a08f6f2f0a21b2f3ae99c1b42a47cee to your computer and use it in GitHub Desktop.
Calculate the average time to read a text
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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