Enea Xharja Logo

Format Reading Time with JavaScript

Reading time is pretty common functionality in blogs.

The formatReadingTime() function below displays cups of coffee as indicators of the minutes it takes to read the post.

js
1function formatReadingTime(timeToRead) {
2 const minutes = `${timeToRead > 1 ? `minutes` : `minute`}`;
3 const cups = Math.round(timeToRead / 5);
4
5 return `${new Array(cups || 1)
6 .fill('☕️')
7 .join('')} ${timeToRead} ${minutes} read`;
8}
9
10formatReadingTime(1); // "☕️ 1 minute read"
11formatReadingTime(9); // "☕️☕️ 9 minutes read"
12formatReadingTime(30); // "☕️☕️☕️☕️☕️☕️ 30 minutes read"