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();
- //returns the raw string in all lower case so that case will not affect matching, clears punctuation, and sorts the array in alphabetical order
- }
- function mostFrequentWord(text) {
- var words = getTokens(text);
- //runs the getTokens function on the entered text
- var wordFrequencies = {};
- //create an empty object for wordFrequencies
- for (var i = 0; i <= words.length; i++) {
- //run the following loop as long as i is less than or equal to length of the words array
- if (words[i] in wordFrequencies) {
- wordFrequencies[words[i]]++;
- }
- else {
- wordFrequencies[words[i]]=1;
- }
- //increment the count for a particular word if found else count is just one
- }
- var currentMaxKey = Object.keys(wordFrequencies)[0];
- //set the var currentMaxKey to the keys of wordFrequencies
- var currentMaxCount = wordFrequencies[currentMaxKey];
- //sets the var currentMaxCount to the currentMaxKey of wordFrequencies
- for (var word in wordFrequencies) {
- //loop through the words in wordFrequencies
- if (wordFrequencies[word] > currentMaxCount) {
- currentMaxKey = word;
- currentMaxCount = wordFrequencies[word];
- //if the word in wordFrequencies is greater than the currentMaxCount, se currentMaxKey to equal the word and the currentMaxCount to equal the word frequencies
- }
- }
- return currentMaxKey;
- //return the results
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement