aboutsummaryrefslogtreecommitdiffstats
path: root/src/utils/helpers/reading-time.ts
blob: 6cdeba41e2234c0d005b7cd46b6c2e5ad99ead23 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
export type GetReadingTimeReturn = {
  /**
   * The reading time rounded to minutes.
   */
  inMinutes: () => number;
  /**
   * The reading time in minutes and seconds.
   */
  inMinutesAndSeconds: () => {
    minutes: number;
    seconds: number;
  };
};

/**
 * Retrieve the reading time from a words count.
 *
 * @param {number} wordsCount - The number of words.
 * @param {number} [wordsPerMinute] - How many words can we read per minute?
 * @returns {GetReadingTimeReturn} Two methods to retrieve the reading time.
 */
export const getReadingTimeFrom = (
  wordsCount: number,
  wordsPerMinute = 245
): GetReadingTimeReturn => {
  const ONE_MINUTE_IN_SECONDS = 60;
  const wordsPerSecond = wordsPerMinute / ONE_MINUTE_IN_SECONDS;
  const estimatedTimeInSeconds = wordsCount / wordsPerSecond;

  return {
    inMinutes: () => Math.round(estimatedTimeInSeconds / ONE_MINUTE_IN_SECONDS),
    inMinutesAndSeconds: () => {
      const estimatedTimeInMinutes = Math.floor(
        estimatedTimeInSeconds / ONE_MINUTE_IN_SECONDS
      );

      return {
        minutes: estimatedTimeInMinutes,
        seconds: Math.round(
          estimatedTimeInSeconds -
            estimatedTimeInMinutes * ONE_MINUTE_IN_SECONDS
        ),
      };
    },
  };
};