aboutsummaryrefslogtreecommitdiffstats
path: root/src/utils/hooks/use-reading-time.tsx
diff options
context:
space:
mode:
authorArmand Philippot <git@armandphilippot.com>2022-05-24 19:35:12 +0200
committerGitHub <noreply@github.com>2022-05-24 19:35:12 +0200
commitc85ab5ad43ccf52881ee224672c41ec30021cf48 (patch)
tree8058808d9bfca19383f120c46b34d99ff2f89f63 /src/utils/hooks/use-reading-time.tsx
parent52404177c07a2aab7fc894362fb3060dff2431a0 (diff)
parent11b9de44a4b2f305a6a484187805e429b2767118 (diff)
refactor: use storybook and atomic design (#16)
BREAKING CHANGE: rewrite most of the Typescript types, so the content format (the meta in particular) needs to be updated.
Diffstat (limited to 'src/utils/hooks/use-reading-time.tsx')
-rw-r--r--src/utils/hooks/use-reading-time.tsx58
1 files changed, 58 insertions, 0 deletions
diff --git a/src/utils/hooks/use-reading-time.tsx b/src/utils/hooks/use-reading-time.tsx
new file mode 100644
index 0000000..fb54135
--- /dev/null
+++ b/src/utils/hooks/use-reading-time.tsx
@@ -0,0 +1,58 @@
+import { useIntl } from 'react-intl';
+
+/**
+ * Retrieve the estimated reading time by words count.
+ *
+ * @param {number} wordsCount - The number of words.
+ * @returns {string} The estimated reading time.
+ */
+const useReadingTime = (
+ wordsCount: number,
+ onlyMinutes: boolean = false
+): string => {
+ const intl = useIntl();
+ const wordsPerMinute = 245;
+ const wordsPerSecond = wordsPerMinute / 60;
+ const estimatedTimeInSeconds = wordsCount / wordsPerSecond;
+
+ if (onlyMinutes) {
+ const estimatedTimeInMinutes = Math.round(estimatedTimeInSeconds / 60);
+
+ return intl.formatMessage(
+ {
+ defaultMessage: '{minutesCount} minutes',
+ description: 'useReadingTime: rounded minutes count',
+ id: 's1i43J',
+ },
+ { minutesCount: estimatedTimeInMinutes }
+ );
+ } else {
+ const estimatedTimeInMinutes = Math.floor(estimatedTimeInSeconds / 60);
+
+ if (estimatedTimeInMinutes <= 0) {
+ return intl.formatMessage(
+ {
+ defaultMessage: '{count} seconds',
+ description: 'useReadingTime: seconds count',
+ id: 'i7Wq3G',
+ },
+ { count: estimatedTimeInSeconds.toFixed(0) }
+ );
+ }
+
+ const remainingSeconds = Math.round(
+ estimatedTimeInSeconds - estimatedTimeInMinutes * 60
+ ).toFixed(0);
+
+ return intl.formatMessage(
+ {
+ defaultMessage: '{minutesCount} minutes {secondsCount} seconds',
+ description: 'useReadingTime: minutes + seconds count',
+ id: 'OevMeU',
+ },
+ { minutesCount: estimatedTimeInMinutes, secondsCount: remainingSeconds }
+ );
+ }
+};
+
+export default useReadingTime;