Advertisement
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
- return rawString.toLowerCase().split(/[ ,!.";:-]+/).filter(Boolean).sort();
- }
- //The provided function mostFrequentWord takes a single argument, text.
- function mostFrequentWord(text) {
- //Declares a variable, words, and it holds the value of the function getTokens which takes a single argument, text.
- let words = getTokens(text);
- //Another variable declaration, wordFrequencies, and it holds the value of an empty object.
- let wordFrequencies = {};
- //Standard notation for a for loop. It means, start with i at 0, and repeat this loop as long as i is less than words.length, and
- //after every loop, increase i by 1 (i++).
- for (let i = 0; i <= words.length; i++) {
- //If the value of variable, words, at the location i in the array, is in wordFrequencies, found through looping through the //object, add 1 to the wordFrequencies
- if (words[i] in wordFrequencies) {
- wordFrequencies[words[i]]++;
- }
- //If the value of variable, words, at location i, is NOT found in, wordFrequencies, set the value of wordFrequencies to 1
- else {
- wordFrequencies[words[i]] = 1;
- }
- }
- //Declares a variable, currentMaxKey, and uses the keys method on the on the object prototype of wordFrequencies.
- let currentMaxKey = Object.keys(wordFrequencies)[0];
- //currentMaxCount variable is declared and it holds the value of the variable wordFrequencies taking the argument currentMaxKey
- let currentMaxCount = wordFrequencies[currentMaxKey];
- //for loop where the variable, word, is declared and the wordFrequencies object is looped through looking for that variable.
- for (let word in wordFrequencies) {
- //if statement where if the variable wordFrequencies when passed the argument, word, is greater than the currentMaxCount, perform //the following block of code.
- if (wordFrequencies[word] > currentMaxCount) {
- //Set the value of currentMaxKey to word.
- currentMaxKey = word;
- //Set the value of currnetMaxCount to wordFrequencies taking the argument, word.
- currentMaxCount = wordFrequencies[word];
- }
- }
- //At last we return the currentMaxKey. The purpose of the function mostFrequentWord is to iterate through objects to
- //return the word used the most throughout the string provided in the function getTokens.
- return currentMaxKey;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement