### Install reading-time-estimator with NPM Source: https://github.com/lbenie/reading-time-estimator/blob/main/README.md Use this command to add the reading-time-estimator package to your project via NPM. ```bash npm install reading-time-estimator ``` -------------------------------- ### Install reading-time-estimator with Yarn Source: https://github.com/lbenie/reading-time-estimator/blob/main/README.md Use this command to add the reading-time-estimator package to your project via Yarn. ```bash yarn add reading-time-estimator ``` -------------------------------- ### Import ReadingTime with CommonJS Source: https://github.com/lbenie/reading-time-estimator/blob/main/_autodocs/exports-and-entry-points.md Shows how to import and use the `readingTime` function in a CommonJS environment, with a concise example. ```javascript const { readingTime } = require('reading-time-estimator') const text = 'Some content to analyze' const result = readingTime(text, { wordsPerMinute: 200 }) console.log(result) ``` -------------------------------- ### Usage Example for German Locale Source: https://github.com/lbenie/reading-time-estimator/blob/main/_autodocs/locales.md Demonstrates how to import and use German translations with the readingTime function. ```typescript import { readingTime } from 'reading-time-estimator' import { de } from 'reading-time-estimator/i18n/de' const result = readingTime('Deutscher Text zum Lesen', { language: 'de', translations: { de } }) // Result: { minutes: ..., words: ..., text: '... Minute Lesedauer' or 'weniger als eine Minute Lesedauer' } ``` -------------------------------- ### Usage Example for Italian Source: https://github.com/lbenie/reading-time-estimator/blob/main/_autodocs/locales.md Demonstrates how to import and use the Italian locale for reading time estimation. Ensure the 'it' locale is included in the translations object. ```typescript import { readingTime } from 'reading-time-estimator' import { it } from 'reading-time-estimator/i18n/it' const result = readingTime('Testo in italiano da leggere', { language: 'it', translations: { it } }) // Result: { minutes: ..., words: ..., text: '... min di lettura' or 'meno di un minuto di lettura' } ``` -------------------------------- ### Usage Example for Brazilian Portuguese Locale Source: https://github.com/lbenie/reading-time-estimator/blob/main/_autodocs/locales.md Demonstrates how to import and use Brazilian Portuguese translations with the readingTime function. ```typescript import { readingTime } from 'reading-time-estimator' import { ptBr } from 'reading-time-estimator/i18n/pt-br' const result = readingTime('Texto em português brasileiro', { language: 'pt-br', translations: { 'pt-br': ptBr } }) // Result: { minutes: ..., words: ..., text: '... min de leitura' or 'menos de um minuto de leitura' } ``` -------------------------------- ### Example: Short English Text Calculation Source: https://github.com/lbenie/reading-time-estimator/blob/main/_autodocs/implementation-details.md Demonstrates the calculation for a short English text with default options. Shows the step-by-step breakdown leading to the final result. ```typescript readingTime("Hello world", {}) // Step 1: options = { wordsPerMinute: 200, language: "en", translations: {}, ... } // Step 2: words = 2 // Step 3: minutes = Math.round(2 / 200) = 0 // Step 4: isLessThanOne = true // Step 5: translation = en.less = "less than a minute read" // Step 6: text = "" + "less than a minute read" = "less than a minute read" // Step 7: return { minutes: 0, words: 2, text: "less than a minute read" } ``` -------------------------------- ### Tokenization Examples Source: https://github.com/lbenie/reading-time-estimator/blob/main/_autodocs/tokenization-and-text-processing.md Illustrates how the tokenizer handles various text inputs, including English, contractions, accented characters, mixed scripts, CJK text, and numbers. ```typescript // Basic English "Hello world" → ["Hello", "world"] (2 tokens) ``` ```typescript // Contractions and hyphens "don't mother-in-law" → ["don't", "mother-in-law"] (2 tokens) ``` ```typescript // Accented characters "café naïve" → ["café", "naïve"] (2 tokens) ``` ```typescript // Mixed scripts "Hello 世界 world" → ["Hello", "世", "界", "world"] (4 tokens) ``` ```typescript // CJK heavy "中文テキスト" → ["中", "文", "テ", "キ", "ス", "ト"] (6 tokens) ``` ```typescript // Numbers "Price: $12.50 or €15,99" → ["Price", "12.50", "15", "99"] (4 tokens after stripping currency symbols via sanitizer) ``` -------------------------------- ### Provide Custom Translations (Simplified Chinese Example) Source: https://github.com/lbenie/reading-time-estimator/blob/main/_autodocs/configuration-and-options.md For Simplified Chinese, import `zhCn` and map it to the `'zh-cn'` key in the `translations` object. ```typescript import { readingTime } from 'reading-time-estimator' import { zhCn } from 'reading-time-estimator/i18n/zh-cn' const result = readingTime('文本', { language: 'zh-cn', translations: { 'zh-cn': zhCn } }) console.log(result.text) // Output: "小于一分钟" or "X分钟" ``` -------------------------------- ### Usage Example for Indonesian Source: https://github.com/lbenie/reading-time-estimator/blob/main/_autodocs/locales.md Demonstrates how to import and use the Indonesian locale for reading time estimation. Ensure the 'id' locale is included in the translations object. ```typescript import { readingTime } from 'reading-time-estimator' import { id } from 'reading-time-estimator/i18n/id' const result = readingTime('Teks dalam bahasa Indonesia untuk dibaca', { language: 'id', translations: { id } }) // Result: { minutes: ..., words: ..., text: '... menit dibaca' or 'kurang dari satu menit dibaca' } ``` -------------------------------- ### Usage Example for Vietnamese Source: https://github.com/lbenie/reading-time-estimator/blob/main/_autodocs/locales.md Demonstrates how to import and use the Vietnamese locale for reading time estimation. Ensure the 'vi' locale is included in the translations object. ```typescript import { readingTime } from 'reading-time-estimator' import { vi } from 'reading-time-estimator/i18n/vi' const result = readingTime('Văn bản tiếng Việt để đọc', { language: 'vi', translations: { vi } }) // Result: { minutes: ..., words: ..., text: '... phút đọc' or 'dưới một phút đọc' } ``` -------------------------------- ### Example: Resolve Translation - English Provided Source: https://github.com/lbenie/reading-time-estimator/blob/main/_autodocs/implementation-details.md Demonstrates retrieving the default translation string when English is explicitly provided in the translations map. ```typescript // English provided resolveTranslation('en', false, { en: {...} }) // → Returns en.default ``` -------------------------------- ### Examples for IsLessThanAMinute Source: https://github.com/lbenie/reading-time-estimator/blob/main/_autodocs/implementation-details.md Demonstrates the behavior of the `isLessThanAMinute` function with various minute inputs, showing its output for values below, at, and above one minute. Useful for verifying the function's logic. ```typescript isLessThanAMinute(0) // true isLessThanAMinute(0.5) // true isLessThanAMinute(0.99) // true isLessThanAMinute(1.0) // false isLessThanAMinute(1.5) // false isLessThanAMinute(10) // false ``` -------------------------------- ### Provide Custom Translations (Japanese Example) Source: https://github.com/lbenie/reading-time-estimator/blob/main/_autodocs/configuration-and-options.md To use Japanese, import the `ja` translation object and pass it within the `translations` map. ```typescript import { readingTime } from 'reading-time-estimator' import { ja } from 'reading-time-estimator/i18n/ja' const result = readingTime('テキスト', { language: 'ja', translations: { ja } }) console.log(result.text) // Output: "1分未満の読み取り" or "X最小読み取り" ``` -------------------------------- ### Example: Resolve Translation - English Requested, Not in Map Source: https://github.com/lbenie/reading-time-estimator/blob/main/_autodocs/implementation-details.md Demonstrates the fallback to built-in English when English is requested but no translations are provided at all. ```typescript // English requested but not in map (shouldn't happen) resolveTranslation('en', false, undefined) // → Uses built-in English ``` -------------------------------- ### Custom HTML Sanitizer Options Example Source: https://github.com/lbenie/reading-time-estimator/blob/main/_autodocs/tokenization-and-text-processing.md Shows how to pass custom `htmlSanitizerOptions` to the `readingTime` function to control which HTML tags and attributes are allowed. ```typescript import { readingTime } from 'reading-time-estimator' const html = '

Hello world

' const result = readingTime(html, { htmlSanitizerOptions: { allowedTags: [], allowedAttributes: {} } }) // Output: { minutes: 0, words: 2, text: 'less than a minute read' } ``` -------------------------------- ### Provide Custom Translations (Spanish Example) Source: https://github.com/lbenie/reading-time-estimator/blob/main/_autodocs/configuration-and-options.md Import the Spanish translation object and include it in the `translations` map to set the output language to Spanish. ```typescript import { readingTime } from 'reading-time-estimator' import { es } from 'reading-time-estimator/i18n/es' const result = readingTime('Algo de texto', { language: 'es', translations: { es } }) console.log(result.text) // Output: "menos de un minuto leyendo" or "X min de lectura" ``` -------------------------------- ### TypeScript: Normalization Example Source: https://github.com/lbenie/reading-time-estimator/blob/main/_autodocs/tokenization-and-text-processing.md Illustrates the effect of space mapping and whitespace collapsing on strings with ideographic spaces, and the effect of NFC normalization on accented characters. ```typescript // Input: "Hello  world" (two ideographic spaces) // After step 2: "Hello world" (two ASCII spaces) // After step 5: "Hello world" (one ASCII space) // Input: "café̈" (e + combining diaeresis) // After step 1: "café" (canonical form) ``` -------------------------------- ### Single Locale Usage Source: https://github.com/lbenie/reading-time-estimator/blob/main/_autodocs/exports-and-entry-points.md Use this example to analyze content with a single, specified locale. Ensure the locale is imported and passed to the readingTime function. ```typescript import { readingTime } from 'reading-time-estimator' import { en } from 'reading-time-estimator/i18n/en' const result = readingTime('Text content', { language: 'en', translations: { en } }) ``` -------------------------------- ### Multilingual Blog Platform Reading Time Estimation Source: https://github.com/lbenie/reading-time-estimator/blob/main/_autodocs/comprehensive-examples.md Integrate reading time estimation for a multilingual blog platform by providing the correct language and translations. This example demonstrates handling English, French, and Spanish content. ```typescript import { readingTime } from 'reading-time-estimator' import { en } from 'reading-time-estimator/i18n/en' import { fr } from 'reading-time-estimator/i18n/fr' import { es } from 'reading-time-estimator/i18n/es' interface LocalizedPost { id: string title: string content: string language: 'en' | 'fr' | 'es' } class BlogService { private translations = { en, fr, es } getReadingTime(post: LocalizedPost) { return readingTime(post.content, { language: post.language, translations: this.translations }) } formatPost(post: LocalizedPost) { const reading = this.getReadingTime(post) return { ...post, readingTime: reading, meta: `${reading.words} words • ${reading.text}` } } } const service = new BlogService() const englishPost: LocalizedPost = { id: '1', title: 'TypeScript Guide', content: 'TypeScript is a typed superset of JavaScript...', language: 'en' } const formatted = service.formatPost(englishPost) console.log(formatted.meta) // "356 words • 2 min read" ``` -------------------------------- ### Markdown to Text Conversion Example Source: https://github.com/lbenie/reading-time-estimator/blob/main/_autodocs/tokenization-and-text-processing.md Demonstrates using the `readingTime` function with Markdown input. The output shows the intermediate parsed HTML and the final sanitized text. ```typescript import { readingTime } from 'reading-time-estimator' const markdown = '# Title\n\nThis is **bold** and *italic* text.' const result = readingTime(markdown) // Parsed to: "

Title

\n

This is bold and italic text.

" // Sanitized to: "Title This is bold and italic text." ``` -------------------------------- ### Usage Example for Japanese Locale Source: https://github.com/lbenie/reading-time-estimator/blob/main/_autodocs/locales.md Demonstrates how to import and use Japanese translations with the readingTime function. Supports Hiragana, Katakana, and Kanji characters, with each CJK character counted as one word. ```typescript import { readingTime } from 'reading-time-estimator' import { ja } from 'reading-time-estimator/i18n/ja' const result = readingTime('日本語のテキスト', { language: 'ja', translations: { ja } }) // Result: { minutes: ..., words: ..., text: '... 最小読み取り' or '1分未満の読み取り' } ``` -------------------------------- ### Multilingual Reading Time Estimation Source: https://github.com/lbenie/reading-time-estimator/blob/main/_autodocs/README.md This example demonstrates how to estimate reading time in different languages by importing and using translation objects. Ensure the correct language code and translations are provided. ```typescript import { readingTime } from 'reading-time-estimator' import { en } from 'reading-time-estimator/i18n/en' import { fr } from 'reading-time-estimator/i18n/fr' import { es } from 'reading-time-estimator/i18n/es' const translations = { en, fr, es } function getReadingTime(articleText, language) { return readingTime(articleText, { language, translations }) } console.log(getReadingTime(text, 'en').text) // "4 min read" console.log(getReadingTime(text, 'fr').text) // "4 min de lecture" console.log(getReadingTime(text, 'es').text) // "4 min de lectura" ``` -------------------------------- ### Example: Long French Text Calculation Source: https://github.com/lbenie/reading-time-estimator/blob/main/_autodocs/implementation-details.md Illustrates the calculation for a longer French text, including custom language and translations. Shows how to import and use French translation data. ```typescript import { fr } from 'reading-time-estimator/i18n/fr' readingTime("Lorem ipsum dolor sit amet... (1000 words)", { language: 'fr', translations: { fr } }) // Step 1: options = { wordsPerMinute: 200, language: "fr", translations: { fr }, ... } // Step 2: words = 1000 // Step 3: minutes = Math.round(1000 / 200) = 5 // Step 4: isLessThanOne = false // Step 5: translation = fr.default = "min de lecture" // Step 6: text = "5 " + "min de lecture" = "5 min de lecture" // Step 7: return { minutes: 5, words: 1000, text: "5 min de lecture" } ``` -------------------------------- ### Multiple Locale Overrides with TranslationMap Source: https://github.com/lbenie/reading-time-estimator/blob/main/_autodocs/types.md Example demonstrating how to override translations for multiple locales (French and Spanish). This allows for granular control over different language outputs. ```typescript // Multiple locales const translations: TranslationMap = { fr: { less: 'moins d\'une minute', default: 'min de lecture' }, es: { less: 'menos de un minuto', default: 'min de lectura' } } ``` -------------------------------- ### Example: Resolve Translation - French Provided Source: https://github.com/lbenie/reading-time-estimator/blob/main/_autodocs/implementation-details.md Demonstrates retrieving the default translation string when the requested language (French) is explicitly provided in the translations map. ```typescript // French provided resolveTranslation('fr', false, { fr: {...} }) // → Returns fr.default ``` -------------------------------- ### Analyze Text in All Supported Languages Source: https://github.com/lbenie/reading-time-estimator/blob/main/_autodocs/comprehensive-examples.md This example shows how to analyze a given text across all 18 supported languages by aggregating all translation objects. It returns an array of results, one for each language. ```typescript import { readingTime } from 'reading-time-estimator' import { en } from 'reading-time-estimator/i18n/en' import { fr } from 'reading-time-estimator/i18n/fr' import { es } from 'reading-time-estimator/i18n/es' import { zhCn } from 'reading-time-estimator/i18n/zh-cn' import { zhTw } from 'reading-time-estimator/i18n/zh-tw' import { ja } from 'reading-time-estimator/i18n/ja' import { de } from 'reading-time-estimator/i18n/de' import { ptBr } from 'reading-time-estimator/i18n/pt-br' import { tr } from 'reading-time-estimator/i18n/tr' import { ro } from 'reading-time-estimator/i18n/ro' import { bn } from 'reading-time-estimator/i18n/bn' import { sk } from 'reading-time-estimator/i18n/sk' import { cs } from 'reading-time-estimator/i18n/cs' import { ru } from 'reading-time-estimator/i18n/ru' import { vi } from 'reading-time-estimator/i18n/vi' import { it } from 'reading-time-estimator/i18n/it' import { id } from 'reading-time-estimator/i18n/id' import { hi } from 'reading-time-estimator/i18n/hi' const allTranslations = { en, fr, es, 'zh-cn': zhCn, 'zh-tw': zhTw, ja, de, 'pt-br': ptBr, tr, ro, bn, sk, cs, ru, vi, it, id, hi } function analyzeInAllLanguages(text) { const languages = Object.keys(allTranslations) return languages.map(lang => ({ language: lang, result: readingTime(text, { language, translations: allTranslations }) })) } const results = analyzeInAllLanguages('Some content to analyze') // Returns array with reading time in all 18 languages ``` -------------------------------- ### Import Locales for Tree-Shaking Source: https://github.com/lbenie/reading-time-estimator/blob/main/_autodocs/README.md Import specific language locales from the i18n directory to enable tree-shaking and reduce bundle size. Examples include English, French, Spanish, and Chinese. ```typescript import { en } from 'reading-time-estimator/i18n/en' import { fr } from 'reading-time-estimator/i18n/fr' import { es } from 'reading-time-estimator/i18n/es' import { zhCn } from 'reading-time-estimator/i18n/zh-cn' ``` -------------------------------- ### Basic Reading Time Estimation Source: https://github.com/lbenie/reading-time-estimator/blob/main/_autodocs/comprehensive-examples.md Use the simplest form of the `readingTime` function to get an estimate for an article. This requires only the article text as input. ```typescript import { readingTime } from 'reading-time-estimator' const article = 'JavaScript is a versatile programming language. It powers interactive web applications.' const result = readingTime(article) console.log(result) // { minutes: 0, words: 16, text: 'less than a minute read' } ``` -------------------------------- ### English Locale Usage Source: https://github.com/lbenie/reading-time-estimator/blob/main/_autodocs/locales.md Use the English locale by importing it and passing it to the readingTime function. This example shows how to set the language to 'en' and provide the English translations. ```typescript export const en: I18n ``` ```typescript import { readingTime } from 'reading-time-estimator' import { en } from 'reading-time-estimator/i18n/en' const result = readingTime('Some text', { language: 'en', translations: { en } }) // Result: { minutes: ..., words: ..., text: '... min read' or 'less than a minute read' } ``` -------------------------------- ### French Locale Usage Source: https://github.com/lbenie/reading-time-estimator/blob/main/_autodocs/locales.md Use the French locale by importing it and passing it to the readingTime function. This example demonstrates setting the language to 'fr' and providing the French translations. ```typescript export const fr: I18n ``` ```typescript import { readingTime } from 'reading-time-estimator' import { fr } from 'reading-time-estimator/i18n/fr' const result = readingTime('Du texte en français', { language: 'fr', translations: { fr } }) // Result: { minutes: ..., words: ..., text: '... min de lecture' or 'moins d\'une minute de lecture' } ``` -------------------------------- ### Example: Resolve Translation - French Requested, Not Provided Source: https://github.com/lbenie/reading-time-estimator/blob/main/_autodocs/implementation-details.md Demonstrates the fallback mechanism when the requested language (French) is not found in the translations map. It will attempt to use `translations.en` or the built-in English. ```typescript // French requested but not provided resolveTranslation('fr', false, { es: {...} }) // → Falls back to translations.en if available, else built-in en ``` -------------------------------- ### Estimate Reading Time with Custom Markdown Parser Options Source: https://github.com/lbenie/reading-time-estimator/blob/main/_autodocs/comprehensive-examples.md Calculate reading time for Markdown content using custom parser options. This example enables line breaks by setting `breaks: true`. ```typescript import { readingTime } from 'reading-time-estimator' const markdown = ` Line 1 Line 2 Line 3 ` // With breaks: true, newlines are converted to
tags const result = readingTime(markdown, { markdownParserOptions: { breaks: true } }) console.log(result) // { minutes: 0, words: 3, text: 'less than a minute read' } ``` -------------------------------- ### React Component for Displaying Reading Time Source: https://github.com/lbenie/reading-time-estimator/blob/main/_autodocs/comprehensive-examples.md Integrate reading time estimation directly into a React component. This example shows how to use the `readingTime` function within a `useMemo` hook for performance optimization. ```typescript import { readingTime } from 'reading-time-estimator' import { en } from 'reading-time-estimator/i18n/en' import React, { useMemo } from 'react' interface BlogPostProps { title: string content: string publishDate: string } export function BlogPost({ title, content, publishDate }: BlogPostProps) { const reading = useMemo( () => readingTime(content, { language: 'en', translations: { en } }), [content] ) return (

{title}

📖 {reading.text}
{content}
) } ``` -------------------------------- ### Security: Block Dangerous Content Source: https://github.com/lbenie/reading-time-estimator/blob/main/_autodocs/configuration-and-options.md Demonstrates how to configure sanitization to block potentially dangerous content, such as script tags, by ensuring only safe tags and attributes are allowed. This example explicitly allows no tags, effectively stripping all HTML. ```typescript import { readingTime } from 'reading-time-estimator' const html = '

Hello

' const result = readingTime(html, { htmlSanitizerOptions: { allowedTags: [], allowedAttributes: {} } }) console.log(result) // Output: { minutes: 0, words: 1, text: 'less than a minute read' } // Script tags completely removed, only "Hello" counted ``` -------------------------------- ### Provide Custom Translations (French Example) Source: https://github.com/lbenie/reading-time-estimator/blob/main/_autodocs/configuration-and-options.md To use a language other than English, import its translation object and provide it in the `translations` map. The `language` option must match the key in the `translations` map. ```typescript import { readingTime } from 'reading-time-estimator' import { fr } from 'reading-time-estimator/i18n/fr' const result = readingTime('Un peu de texte', { language: 'fr', translations: { fr } }) console.log(result.text) // Output: "moins d'une minute de lecture" or "X min de lecture" ``` -------------------------------- ### Edge Cases for GetNumberOfWords Source: https://github.com/lbenie/reading-time-estimator/blob/main/_autodocs/implementation-details.md Illustrates how `getNumberOfWords` handles various edge cases, including empty input, whitespace-only input, double spaces, and CJK text. These examples are useful for testing and understanding the robustness of the word counting mechanism. ```typescript // Empty input → 0 words getNumberOfWords("") // Whitespace only → 0 words getNumberOfWords(" ") // Double spaces (tokenizes to ["word", "", "word"]) → 2 words getNumberOfWords("word word") // CJK text (each character is a token) → counts characters getNumberOfWords("中文") // → 2 ``` -------------------------------- ### Import Main Entry Point Source: https://github.com/lbenie/reading-time-estimator/blob/main/_autodocs/exports-and-entry-points.md Illustrates how to import the main `readingTime` function and related types from the library. ```typescript import { readingTime } from 'reading-time-estimator' import type { ReadingTime, Options, SupportedLanguages } from 'reading-time-estimator' ``` -------------------------------- ### Configure User-Facing Blog with Custom Strings Source: https://github.com/lbenie/reading-time-estimator/blob/main/_autodocs/configuration-and-options.md Customize the output text by providing your own translations for 'less' and 'default' read time indicators. ```typescript import { readingTime } from 'reading-time-estimator' const customTranslations = { en: { less: '⚡ Quick read', default: 'min read' } } const result = readingTime('Article content...', { wordsPerMinute: 200, language: 'en', translations: customTranslations }) console.log(result.text) // "⚡ Quick read" or "X min read" ``` -------------------------------- ### Import Main Entry Point and Types Source: https://github.com/lbenie/reading-time-estimator/blob/main/_autodocs/README.md Import the primary `readingTime` function and associated types like `ReadingTime` and `Options` from the main library entry point. ```typescript import { readingTime, type ReadingTime, type Options } from 'reading-time-estimator' ``` -------------------------------- ### Package.json Exports Configuration Source: https://github.com/lbenie/reading-time-estimator/blob/main/_autodocs/exports-and-entry-points.md Defines the main and internationalization entry points for the library, specifying types and module formats for import and require. ```json { "exports": { ".": { "types": "./dist/types/reading-time-estimator.d.ts", "import": "./dist/index.js", "require": "./dist/index.cjs" }, "./i18n/en": { "types": "./dist/types/i18n/en.d.ts", "import": "./dist/i18n/en/locale.js", "require": "./dist/i18n/en/locale.cjs" }, "./i18n/fr": { ... }, "./i18n/es": { ... }, "./i18n/zh-cn": { ... }, "./i18n/zh-tw": { ... }, "./i18n/ja": { ... }, "./i18n/de": { ... }, "./i18n/pt-br": { ... }, "./i18n/tr": { ... }, "./i18n/ro": { ... }, "./i18n/bn": { ... }, "./i18n/sk": { ... }, "./i18n/cs": { ... }, "./i18n/ru": { ... }, "./i18n/vi": { ... }, "./i18n/it": { ... }, "./i18n/id": { ... }, "./i18n/hi": { ... }, "./package.json": "./package.json" } } ``` -------------------------------- ### Single Locale Override with TranslationMap Source: https://github.com/lbenie/reading-time-estimator/blob/main/_autodocs/types.md Example of overriding translations for a single locale (French). Only the specified language's translations will be custom. ```typescript // Single locale override const translations: TranslationMap = { fr: { less: 'custom French less', default: 'custom French default' } } ``` -------------------------------- ### Configure for Multilingual Blog Platform Source: https://github.com/lbenie/reading-time-estimator/blob/main/_autodocs/configuration-and-options.md Import and provide multiple language translations to handle content in different languages. A helper function can abstract the language selection. ```typescript import { readingTime } from 'reading-time-estimator' import { en } from 'reading-time-estimator/i18n/en' import { fr } from 'reading-time-estimator/i18n/fr' import { es } from 'reading-time-estimator/i18n/es' const translations = { en, fr, es } function getReadingTime(content, language) { return readingTime(content, { wordsPerMinute: 200, language, translations }) } console.log(getReadingTime('Some content', 'en')) // English output console.log(getReadingTime('Du contenu', 'fr')) // French output console.log(getReadingTime('Algún contenido', 'es')) // Spanish output ``` -------------------------------- ### Import Locales with CommonJS Source: https://github.com/lbenie/reading-time-estimator/blob/main/_autodocs/exports-and-entry-points.md Import specific locale modules using CommonJS syntax. This is suitable for Node.js environments or older build setups. ```javascript const { en } = require('reading-time-estimator/i18n/en') const { fr } = require('reading-time-estimator/i18n/fr') ``` -------------------------------- ### Get Number of Words Function Signature Source: https://github.com/lbenie/reading-time-estimator/blob/main/_autodocs/tokenization-and-text-processing.md Defines the function signature for counting words in a given string, accepting sanitizer and markdown options. ```typescript const getNumberOfWords = ( data: string, sanitizerOptions: Readonly, markdownOptions: Readonly ): number ``` -------------------------------- ### Re-exporting Types and Main Function Source: https://github.com/lbenie/reading-time-estimator/blob/main/_autodocs/exports-and-entry-points.md Demonstrates how to re-export types and the main function from a library's entry point file. This is common practice for organizing exports and providing a clean API. ```typescript // From lib/reading-time-estimator.ts // Re-export types export type { SupportedLanguages } from "./i18n/types.js" export type { Options, ReadingTime } from "./types.js" // Re-export constants export { supportedLanguages } from "./i18n/types.js" // Export main function export const readingTime = (data: string, options?: Options): ReadingTime => { // ... implementation } ``` -------------------------------- ### Bundle Size Estimates Source: https://github.com/lbenie/reading-time-estimator/blob/main/_autodocs/implementation-details.md Provides estimates for the minified bundle sizes of the core library, locales, and dependencies. Useful for understanding the library's footprint. ```text Core library (readingTime + helpers): ~1-1.5 KB (minified) Single locale (e.g., en): ~0.2 KB (minified) All 18 locales: ~3.6 KB (minified) Dependencies: ~10-15 KB (minified) Total with core + all locales: ~14-18 KB (minified + gzipped) ``` -------------------------------- ### Main Entry Point: readingTime Function Source: https://github.com/lbenie/reading-time-estimator/blob/main/_autodocs/exports-and-entry-points.md The `readingTime` function is the primary export for estimating reading time. It accepts the text content and an optional options object for configuration. ```APIDOC ## readingTime(text: string, options?: Options) ### Description Main function for reading time estimation. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **text** (string) - Required - The text content to analyze. - **options** (Options) - Optional - Configuration parameters for estimation. - **wordsPerMinute** (number) - Optional - The average words per minute for estimation. Defaults to 200. - **language** (SupportedLanguages) - Optional - The language of the text for accurate estimation. Defaults to 'en'. ### Returns - **ReadingTime** - An object containing the estimated reading time details. - **text** (string) - The original text analyzed. - **words** (number) - The total number of words in the text. - **minutes** (number) - The estimated reading time in minutes. - **time** (number) - The estimated reading time in milliseconds. - **wordsPerMinute** (number) - The words per minute used for estimation. - **language** (SupportedLanguages) - The language used for estimation. ### Example: ES Module ```typescript import { readingTime, type Options, type ReadingTime } from 'reading-time-estimator' const text = 'Some content to analyze' const options: Options = { wordsPerMinute: 200, language: 'en' } const result: ReadingTime = readingTime(text, options) console.log(result) ``` ### Example: CommonJS ```javascript const { readingTime } = require('reading-time-estimator') const text = 'Some content to analyze' const result = readingTime(text, { wordsPerMinute: 200 }) console.log(result) ``` ``` -------------------------------- ### Vite Build Configuration for Library Source: https://github.com/lbenie/reading-time-estimator/blob/main/_autodocs/exports-and-entry-points.md Configures Vite to build a library with multiple entry points and output formats (ESM and CJS). Useful for creating distributable packages. ```typescript // vite.config.ts export default { build: { lib: { entry: { index: 'lib/reading-time-estimator.ts', 'i18n/en/locale': 'lib/i18n/en.ts', 'i18n/fr/locale': 'lib/i18n/fr.ts', // ... all other locales }, formats: ['es', 'cjs'] } } } ``` -------------------------------- ### Import ReadingTime with ES Modules Source: https://github.com/lbenie/reading-time-estimator/blob/main/_autodocs/exports-and-entry-points.md Demonstrates importing and using the `readingTime` function with specific options in an ES Module environment. ```typescript import { readingTime, type Options, type ReadingTime } from 'reading-time-estimator' const text = 'Some content to analyze' const options: Options = { wordsPerMinute: 200, language: 'en' } const result: ReadingTime = readingTime(text, options) console.log(result) ``` -------------------------------- ### Estimate Reading Time for Text Source: https://github.com/lbenie/reading-time-estimator/blob/main/_autodocs/README.md Use this snippet to get an estimated reading time for a given text. It returns an object with properties like 'text' for a human-readable string. ```typescript import { readingTime } from 'reading-time-estimator' const result = readingTime('Your article text here') console.log(result.text) // "7 min read" or "less than a minute read" ``` -------------------------------- ### Bundle Size Optimization with Tree Shaking Source: https://github.com/lbenie/reading-time-estimator/blob/main/_autodocs/configuration-and-options.md Compares the bundle size impact of including all locales versus selectively importing only necessary ones. Tree shaking significantly reduces the final bundle size. ```typescript // Without tree-shaking: all 18 locales bundled import { readingTime } from 'reading-time-estimator' // ~5kb // With tree-shaking: only needed locales import { readingTime } from 'reading-time-estimator' import { en } from 'reading-time-estimator/i18n/en' // ~0.2kb per locale import { fr } from 'reading-time-estimator/i18n/fr' // Result: ~0.6kb total for core + 2 locales ``` -------------------------------- ### Estimate Reading Time for a Simple Blog Post Source: https://github.com/lbenie/reading-time-estimator/blob/main/_autodocs/comprehensive-examples.md Use this snippet to calculate the reading time for a single blog post. Ensure the 'reading-time-estimator' and its English translations are imported. ```typescript import { readingTime } from 'reading-time-estimator' import { en } from 'reading-time-estimator/i18n/en' interface BlogPost { title: string content: string readingTime?: { minutes: number; words: number; text: string } } function processBlogPost(post: BlogPost): BlogPost { return { ...post, readingTime: readingTime(post.content, { language: 'en', translations: { en } }) } } const post: BlogPost = { title: 'Getting Started with TypeScript', content: 'TypeScript adds static typing to JavaScript...' // 2000+ words } const processed = processBlogPost(post) console.log(`Reading time: ${processed.readingTime?.text}`) // Output: "Reading time: 10 min read" ``` -------------------------------- ### Resolve Translation String Source: https://github.com/lbenie/reading-time-estimator/blob/main/_autodocs/implementation-details.md Use this function to get the correct translation string for a given language and context. It handles fallbacks to English if the requested language or its English equivalent is not found in the provided translations. ```typescript const resolveTranslation = ( language: SupportedLanguages, isLessThanOne: boolean, translations?: TranslationMap ) => { const locale: I18n = translations?.[language] ?? (language === "en" ? en : (translations?.en ?? en)) return locale[isLessThanOne ? "less" : "default"] } ``` -------------------------------- ### Configure for Academic Paper Analysis Source: https://github.com/lbenie/reading-time-estimator/blob/main/_autodocs/configuration-and-options.md Use a slower wordsPerMinute setting for technical content. Ensure the correct language and translations are provided. ```typescript import { readingTime } from 'reading-time-estimator' import { en } from 'reading-time-estimator/i18n/en' const paper = '# Research Title\n\nAbstract and content...' const result = readingTime(paper, { wordsPerMinute: 150, // Slower for technical content language: 'en', translations: { en } }) console.log(result) // Example: { minutes: 45, words: 6750, text: '45 min read' } ``` -------------------------------- ### Handle Short Content and Rounding Source: https://github.com/lbenie/reading-time-estimator/blob/main/_autodocs/comprehensive-examples.md Demonstrates how the estimator rounds reading time for very short content. Content with 0-199 words is considered 'less than a minute read'. ```typescript import { readingTime } from 'reading-time-estimator' // With default 200 WPM: // 0-199 words → 0 minutes → "less than a minute" // 200-399 words → 1 minute → "1 min read" // 400-599 words → 2 minutes → "2 min read" const oneWord = 'Hello' const twoHundredWords = Array(200).fill('word').join(' ') const threeHundredWords = Array(300).fill('word').join(' ') console.log(readingTime(oneWord)) // { minutes: 0, words: 1, text: 'less than a minute read' } console.log(readingTime(twoHundredWords)) // { minutes: 1, words: 200, text: '1 min read' } console.log(readingTime(threeHundredWords)) // { minutes: 2, words: 300, text: '2 min read' } ``` -------------------------------- ### Get Number Of Words Function Source: https://github.com/lbenie/reading-time-estimator/blob/main/_autodocs/implementation-details.md Counts the total number of non-empty words in the input text by leveraging the `parseWords` function and reducing the token array. Use for obtaining a raw word count before time estimation. ```typescript const getNumberOfWords = ( data: string, sanitizerOptions: Readonly, markdownOptions: Readonly, ) => parseWords(data, sanitizerOptions, markdownOptions).reduce( (accumulator, token) => accumulator + (token.trim().length ? 1 : 0), 0, ) ``` -------------------------------- ### Basic Reading Time Estimation (English) Source: https://github.com/lbenie/reading-time-estimator/blob/main/_autodocs/api-reference.md Calculate reading time for English text using default settings. Imports the `readingTime` function. ```typescript import { readingTime } from 'reading-time-estimator' const text = 'JavaScript is a versatile language used for web development. It powers interactive web applications.' const result = readingTime(text) console.log(result) // Output: { minutes: 0, words: 18, text: 'less than a minute read' } ``` -------------------------------- ### Use Multiple Locales for Translations Source: https://github.com/lbenie/reading-time-estimator/blob/main/_autodocs/configuration-and-options.md Shows how to provide translations for multiple languages simultaneously. Ensure to import the necessary locale data. ```typescript import { readingTime } from 'reading-time-estimator' import { en } from 'reading-time-estimator/i18n/en' import { fr } from 'reading-time-estimator/i18n/fr' import { es } from 'reading-time-estimator/i18n/es' const translations = { en, fr, es } const frResult = readingTime('Texte français', { language: 'fr', translations }) const esResult = readingTime('Texto español', { language: 'es', translations }) console.log(frResult.text) // "... min de lecture" or "moins d'une minute de lecture" console.log(esResult.text) // "... min de lectura" or "menos de un minuto leyendo" ``` -------------------------------- ### Spanish Locale Usage Source: https://github.com/lbenie/reading-time-estimator/blob/main/_autodocs/locales.md Demonstrates how to import and use the Spanish locale with the reading time estimator. Ensure the 'es' locale is provided in the translations object. ```typescript import { readingTime } from 'reading-time-estimator' import { es } from 'reading-time-estimator/i18n/es' const result = readingTime('Texto en español', { language: 'es', translations: { es } }) // Result: { minutes: ..., words: ..., text: '... min de lectura' or 'menos de un minuto leyendo' } ``` -------------------------------- ### Options Type Source: https://github.com/lbenie/reading-time-estimator/blob/main/_autodocs/types.md The `Options` type defines the configuration object that can be passed to the `readingTime` function to customize its behavior. ```APIDOC ## Options Type Definition ### Description Configuration object to customize the `readingTime` function's behavior. ### Type Definition ```typescript type Options = { readonly wordsPerMinute?: number; readonly language?: SupportedLanguages; readonly translations?: TranslationMap; readonly htmlSanitizerOptions?: Readonly; readonly markdownParserOptions?: Readonly; } ``` ### Fields | Field | Type | Required | Default | Description | |-------|------|----------|---------|-------------| | `wordsPerMinute` | `number` | no | `200` | Average reading speed in words per minute. Used to calculate total reading time: `minutes = Math.round(wordCount / wordsPerMinute)`. Typical values range from 150–300 depending on text complexity and reader proficiency. | | `language` | `SupportedLanguages` | no | `'en'` | ISO locale code for output text translation. Must match one of the supported language codes or the function falls back to English. See `SupportedLanguages` for complete list. | | `translations` | `TranslationMap` | no | `{}` | Partial map of language codes to `I18n` objects for custom translations. Allows overriding default locale strings or adding custom translations. If a requested language is not in the map, falls back to English. | | `htmlSanitizerOptions` | `Readonly` | no | `{ allowedTags: [], allowedAttributes: {} }` | Configuration passed to the `sanitize-html` library. Controls which HTML tags and attributes are preserved during parsing. Default removes all tags and attributes for security. | | `markdownParserOptions` | `Readonly` | no | `{}` | Configuration passed to the `marked` library for Markdown parsing. The `async` property is always internally set to `false` and cannot be overridden. Custom options modify tokenization and rendering behavior. | ### Used By - Parameter type for [`readingTime()`](./api-reference.md#readingtime) function ``` -------------------------------- ### Import and Use Hindi Translations Source: https://github.com/lbenie/reading-time-estimator/blob/main/_autodocs/locales.md Demonstrates how to import the Hindi translation object and use it with the readingTime function. Ensure the language code 'hi' is specified. ```typescript import { readingTime } from 'reading-time-estimator' import { hi } from 'reading-time-estimator/i18n/hi' const result = readingTime('हिंदी पाठ को पढ़ने के लिए', { language: 'hi', translations: { hi } }) // Result: { minutes: ..., words: ..., text: '... मिनट पढ़ना' or 'एक मिनट से कम पढ़ना' } ``` -------------------------------- ### Import Locale Modules Source: https://github.com/lbenie/reading-time-estimator/blob/main/_autodocs/locales.md Import locale modules using the specified pattern. Each locale is independently importable to support tree-shaking and minimize bundle size. ```typescript import { EXPORT_NAME } from 'reading-time-estimator/i18n/{code}' ``` ```typescript import { en } from 'reading-time-estimator/i18n/en' import { fr } from 'reading-time-estimator/i18n/fr' import { zhCn } from 'reading-time-estimator/i18n/zh-cn' ``` -------------------------------- ### Import Reading Time Estimator (ESM) Source: https://github.com/lbenie/reading-time-estimator/blob/main/_autodocs/README.md Use this import statement for projects utilizing ECMAScript Modules. ```javascript import { readingTime } from 'reading-time-estimator' ``` -------------------------------- ### Import Pattern for Locales Source: https://github.com/lbenie/reading-time-estimator/blob/main/_autodocs/exports-and-entry-points.md Use this pattern to import specific locale translations for tree-shaking. Replace {code} with the desired locale code. ```typescript import { EXPORT_NAME } from 'reading-time-estimator/i18n/{code}' ``` -------------------------------- ### Supported Types and Constants Source: https://github.com/lbenie/reading-time-estimator/blob/main/_autodocs/exports-and-entry-points.md Exposes types and constants for working with the reading time estimator, including supported languages. ```APIDOC ## Types and Constants ### Exports | Symbol | Type | Description | |--------|------|-------------| | `readingTime` | function | Main function for reading time estimation | | `ReadingTime` | type | Return type object shape | | `Options` | type | Configuration parameter type | | `SupportedLanguages` | type | Union type of supported language codes | | `supportedLanguages` | const | Array of all supported language code strings | ``` -------------------------------- ### Default HTML Sanitization: Strip All Tags Source: https://github.com/lbenie/reading-time-estimator/blob/main/_autodocs/configuration-and-options.md Demonstrates the default behavior of stripping all HTML tags and attributes, resulting in plain text for word count and reading time calculation. This is the default when no specific htmlSanitizerOptions are provided. ```typescript import { readingTime } from 'reading-time-estimator' const html = '

Hello world

' const result = readingTime(html) console.log(result) // Output: { minutes: 0, words: 2, text: 'less than a minute read' } // Parsed as: "Hello world" ``` -------------------------------- ### typesVersions for Locale Subpath Resolution Source: https://github.com/lbenie/reading-time-estimator/blob/main/_autodocs/exports-and-entry-points.md Use the 'typesVersions' field in package.json to ensure correct type resolution for locale subpaths. ```json { "typesVersions": { "*": { "i18n/*": [ "./dist/types/i18n/*" ] } } } ``` -------------------------------- ### Handle Empty and Whitespace Content Source: https://github.com/lbenie/reading-time-estimator/blob/main/_autodocs/comprehensive-examples.md The estimator correctly returns 0 minutes and 0 words for empty strings, whitespace-only strings, and strings with only newlines. ```typescript import { readingTime } from 'reading-time-estimator' const empty = '' const whitespace = ' ' const onlyNewlines = '\n\n\n' console.log(readingTime(empty)) // { minutes: 0, words: 0, text: 'less than a minute read' } console.log(readingTime(whitespace)) // { minutes: 0, words: 0, text: 'less than a minute read' } console.log(readingTime(onlyNewlines)) // { minutes: 0, words: 0, text: 'less than a minute read' } ``` -------------------------------- ### TypeScript Module Resolution Configuration Source: https://github.com/lbenie/reading-time-estimator/blob/main/_autodocs/exports-and-entry-points.md Configure TypeScript's module resolution to 'node' and module format to 'esnext' for optimal compatibility. ```json { "compilerOptions": { "moduleResolution": "node", "module": "esnext" } } ```