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();
- }
- function mostFrequentWord(text) {
- //this is saying we will use a function called mostFrequentWord that will have text as its only parameter
- var words = getTokens(text);
- //now we are making a variable called words that will basically be the getTokens function
- //declared above(puts the strings to lowercase and sorts)
- var wordFrequencies = {};
- //now, wordFrequencies is an object, but it is currently empty
- for (var i = 0; i <= words.length; i++) {
- //this is a for loop. we are saying some variable (called i) will start at the 0 spot in an array - it will continue as
- //long as this is less than or equal to the length of the array - once we do the stuff below in the for loop, add 1
- if (words[i] in wordFrequencies) {
- //this is the beginning of an if statement - it says if the i variable in the words array is in the wordFrequency object...
- wordFrequencies[words[i]]++;
- }
- // (continued from prev line), then add 1 to wordFrequencies (to increase the counter)
- else {
- wordFrequencies[words[i]]=1;
- }
- //if the previous statement is not true, then leave the word frequency to 1
- }
- var currentMaxKey = Object.keys(wordFrequencies)[0];
- //this is an Object.key function. this is being used because you need to pair words (keys) to their wordFrequencies (values)
- var currentMaxCount = wordFrequencies[currentMaxKey];
- //we created a currentMaxCount variable because eventually, we want this to hold the word with the highest frequency
- for (var word in wordFrequencies) {
- //opening another for loop...
- if (wordFrequencies[word] > currentMaxCount) {
- //part of the for loop.. if the wordFrequencies var that we made a loop for before is begger than the currentMaxCount just created...
- currentMaxKey = word;
- //currentMaxKey then equals the word (basically, stop there)
- currentMaxCount = wordFrequencies[word];
- //similar to line above
- }
- }
- return currentMaxKey;
- //the answer of the most frequently used word is now in this key, so return/display it
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement