Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function getTokens(rawString) {
- // NB: `.filter(Boolean)` removes any falsy items from an array
- // we receive a string, .toLowerCase makes it all toLowerCase
- // split() returns an array of strings seporated on what we passed into it. so breaking it up into words
- // finally .sort() sorts alphabetically
- return rawString.toLowerCase().split(/[ ,!.";:-]+/).filter(Boolean).sort();
- }
- //
- function mostFrequentWord(text) { // pass in a string variable
- let words = getTokens(text); // send string variable to the getTokens function and recieve an array of words, this array is sorted alphabetically
- let wordFrequencies = {}; // Create an object with no properties
- for (let i = 0; i <= words.length; i++) { // Loop through our array
- if (words[i] in wordFrequencies) { // if the word is already a key in our object
- wordFrequencies[words[i]]++; // then increment the value
- } else { // if it isn't already a key in our object
- wordFrequencies[words[i]] = 1; // then create it and set its value to 1
- }
- }
- let currentMaxKey = Object.keys(wordFrequencies)[0]; // create a variable and assign the name of the first key (or word) to it
- let currentMaxCount = wordFrequencies[currentMaxKey]; // create a variable and assign the value of that first key to it
- for (let word in wordFrequencies) { // loop through the object
- if (wordFrequencies[word] > currentMaxCount) { // if the value is higher than the current max
- currentMaxKey = word; // reset the highest variables to these values
- currentMaxCount = wordFrequencies[word];
- }
- }
- return currentMaxKey; // return the name of the key that has the highest value. In other words . . . the word that shows up the most in the paragraph sent to us.
- }
Add Comment
Please, Sign In to add comment