Enea Xharja

Format Reading Time with JavaScript

Reading time is a pretty common functionality in blogs.

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

function formatReadingTime(timeToRead) {
  const minutes = `${timeToRead > 1 ? `minutes` : `minute`}`;
  const cups = Math.round(timeToRead / 5);

  return `${new Array(cups || 1)
    .fill('☕️')
    .join('')} ${timeToRead} ${minutes} read`;
}

formatReadingTime(1); // "☕️ 1 minute read"
formatReadingTime(9); // "☕️☕️ 9 minutes read"
formatReadingTime(30); // "☕️☕️☕️☕️☕️☕️ 30 minutes read"

Updated on July 04, 2020

Tagged with: javascript, snippets


Profile picture

Hey there! I'm Enea, a web developer currently working at eqolot. Welcome to my little corner of the web, where I share my personal collection of notes, code snippets, and resources on topics that interest me.

© 2021 Enea Xharja