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
- // .lowercase changes all words in the array to lowercase and .split removes and of the characterd in the braces
- return rawString.toLowerCase().split(/[ ,!.";:-]+/).filter(Boolean).sort();
- }
- //this line is declaring the function and using (text) as the argument.
- function mostFrequentWord(text) {
- // the variable words has been declared as the getTokens Function from above and text is the argument.
- //getTokens puts all of the words in the string into an array
- var words = getTokens(text);
- // the variable wordFrequencies is being declared as an object that has not been defined yet that the words from
- //the array will be put into
- var wordFrequencies = {};
- //this is a for loop that has been created to go through the words array that is in the getTokens function and
- //going to go through the full length of the array
- for (var i = 0; i <= words.length; i++) {
- // this is if statement will be run through each loop. If anything in words index is in wordFrequencies the
- //statement below it will be run and keep adding 1 more to it
- if (words[i] in wordFrequencies) {
- wordFrequencies[words[i]]++;
- }
- //if the if statement above does not eqaul to true then this else statement will run. If there is no more then 1 of the
- // specific word it will just = 1
- else {
- wordFrequencies[words[i]]=1;
- }
- }
- // the currentMaxKey is the list of keys with an object
- var currentMaxKey = Object.keys(wordFrequencies)[0];
- //the variable currentMaxCount is being declared as the currentMaxKey that is declared above from the
- //wordFrequencies array
- var currentMaxCount = wordFrequencies[currentMaxKey];
- //this is a for loop that will be run through the properties word in the wordFrequencies object
- for (var word in wordFrequencies) {
- // this is an if statement that will execute if wordFrequencies[word] is greater then currentMaxCount. The word with the current
- // max count will be the one that takes p
- if (wordFrequencies[word] > currentMaxCount) {
- // the var currentMaxKey should be declared as word - the workd is the value of the highest count
- //and the var currentMaxCount will be declared as wordFrequencies[word];
- currentMaxKey = word;
- currentMaxCount = wordFrequencies[word];
- }
- }
- //Returns the key value of the most used word
- return currentMaxKey;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement