Hey fellow developers! Today, I want to share a handy TypeScript function I recently implemented to enhance the user experience of my blog. One common feature that readers appreciate is an estimated reading time for each blog post. Not only does it provide valuable information upfront, but it also helps users manage their time better. Let's dive into how we can achieve this with TypeScript.

Understanding the Approach

Before we jump into code, let's outline our approach. We'll calculate the reading time based on the total word count of the blog post content. Additionally, we'll consider other media elements like images and videos, adjusting the reading time accordingly. With TypeScript, we'll ensure type safety and clarity in our implementation.

To calculate the reading time of a blog post that includes various types of media, we'll follow these steps:

  1. Estimate Text Reading Time: Calculate the reading time based on the text content of the blog post using the average reading speed assumption.
  2. Estimate Media Viewing Time: Estimate the time it takes to view each type of media (e.g., images, videos) and sum them up.
  3. Combine Text and Media Times: Add the estimated text reading time to the total media viewing time to get the overall estimated reading time.


Implementation

Here's how we can implement the reading time calculator function like this:


function calculateReadingTime(content: string): number {
  // Assuming average reading speed of 200 words per minute
  const wordsPerMinute = 200;

  // Calculate word count of the text content
  const wordCount = content.replace(/<[^>]+>/g, " ").split(/\s+/).length;

  // Calculate estimated reading time for text content
  const textReadingTime = Math.ceil(wordCount / wordsPerMinute);

  // Estimate media viewing time (adjust as needed)
  const mediaTypes: Record<string, number> = {
    image: 10, // 10 seconds per image
    video: 120, // 2 minutes per video
  };

  let totalMediaTime = 0;

  Object.keys(mediaTypes).forEach((mediaType) => {
    const mediaCount = (content.match(new RegExp(`<${mediaType}`, "gi")) || [])
      .length;
    totalMediaTime += mediaCount * mediaTypes[mediaType];
  });

  // Convert media time from seconds to minutes
  const mediaReadingTime = Math.ceil(totalMediaTime / 60);

  // Combine text and media reading times
  const totalReadingTime = textReadingTime + mediaReadingTime;

  return totalReadingTime;
}

// Example usage
const blogPostContent = `
  <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
  <img src="image1.jpg" alt="Image 1">
  <p>Fusce consectetur tellus vel nunc mattis, id tempus leo consectetur.</p>
  <video src="video1.mp4" controls autoplay loop muted></video>
  <p>Mauris dignissim vestibulum massa, quis ullamcorper velit tristique vel.</p>
`;

const readingTime = calculateReadingTime(blogPostContent);

console.log(`Estimated reading time: ${readingTime} minutes`);


Conclusion

By implementing this reading time calculator function, we can provide readers with a more informative and user-friendly experience on our blog. TypeScript's static typing helps ensure the reliability and maintainability of our codebase, while the calculation logic accurately estimates the reading time based on the content's word count and media elements. I hope you find this tip useful for your own projects!

Happy coding! 🚀