Skip to content

Instantly share code, notes, and snippets.

@mvark
Last active November 15, 2023 03:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mvark/7aefdc837ea1acfecf5a237c15e5ffc3 to your computer and use it in GitHub Desktop.
Save mvark/7aefdc837ea1acfecf5a237c15e5ffc3 to your computer and use it in GitHub Desktop.
Bookmarklet code to calculate Word Count & Estimated Reading Time
// Code generated by Bard
// IIFE (Immediately Invoked Function Expression) is used to encapsulate the code within a function to avoid polluting the global namespace and execute it immediately
//default parameter is used to set the initial value of the wordsPerMinute variable to 200 assuming assuming that words-per-minute rate for reading. You can adjust this value based on your preferred reading speed.
javascript:(function(wordsPerMinute = 200) {
// selected text from the webpage is trimmed of any leading or trailing whitespaces
const selectedText = window.getSelection().toString().trim();
// We proceed to calculate the estimated reading time based on the selected text or all words in the body
// single ternary expression is used instead of if statements
// window.getSelection().toString().trim() gets the selected text
// document.body.innerText.trim() gets the entire text content of the page if nothing is selected
// The selected or retrieved text is split into an array of words using the regular expression /\s+/
// The word count is calculated based on the length of the array
const totalWords = selectedText ? selectedText.split(/\s+/).length : document.body.innerText.split(/\s+/).length;
//Math.ceil() function is used to round the estimated time up to the nearest integer.
const estimatedTime = Math.ceil(totalWords / wordsPerMinute);
//template literals to format the alert message
alert(`Word count: ${totalWords}\nEstimated reading time: ${estimatedTime} minutes`);
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment