How to create an Angular pipe that gives an estimation of reading time

We are going to create a simple pipe that will show our readers an average time to read estimation.

read-time.png

Sometimes it’s a necessity for a company or brand to create a blog. These blog posts can be very large, so wouldn’t it be nice if we could show readers an estimation of reading time for a specific article?

In this post, we are going to create a pipe that will estimate how long an article will take to read.

  1. If you don’t have a project yet, create a new Angular project.
ng new demo-read-time
  1. Install moment
yarn add moment
//or
npm install moment
  1. Create a new pipe like so:
ng g pipe read-time
  1. Within this pipe add the following code:
import { Pipe, PipeTransform } from '@angular/core';
import * as moment from 'moment';
import DurationConstructor = moment.unitOfTime.DurationConstructor;

@Pipe({
  name: 'readingTime'
})
export class ReadingTimePipe implements PipeTransform {
  transform(content: string, wpm: number = 575, unit: DurationConstructor = 'minutes', locale = 'en'): string {
    const words = text.trim().split(/\s+/).length;
    const duration = Math.ceil(words / wpm);
    return moment.duration(duration, unit).locale(locale).humanize();
  }
}

This piece of code has 4 parameters, the content would be the text of an article/post. wpm stands for words per minute, we can expect the following:

  • Third-grade students = 150 wpm
  • Eighth grade students = 250 wpm
  • Average college student = 450 wpm
  • Average “high-level exec” = 575 wpm
  • Average college professor = 675 wpm
  • Speed readers = 1,500 wpm

The unit parameter is the duration, and locale is used to define the language with moment.

Now we can use the pipe as follow:

<p>{{ content | readingTime }}</p>

Thats all folks, thank you for reading this post.

logo-stackblitz copy

Go to stackblitz

@ Copyright Vonlof (Edept B.V.) info@vonlof.com