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
- //this function returns an array of words from rawString split at the characters [ ,!.";:-]+ all lower-cased and sorted alphabetically
- return rawString.toLowerCase().split(/[ ,!.";:-]+/).filter(Boolean).sort();
- }
- function mostFrequentWord(text) {
- //we get an array of words from text that is ordered
- let words = getTokens(text);
- //this object keeps track of each time a word is mentioned
- let wordFrequencies = {};
- //we loop through the array and add it to our object or increment it's value by 1
- for (let i = 0; i <= words.length; i++) {
- if (words[i] in wordFrequencies) {
- wordFrequencies[words[i]]++;
- } else {
- wordFrequencies[words[i]] = 1;
- }
- }
- //currentMaxKey keeps track of the key that has the max value in the object
- let currentMaxKey = Object.keys(wordFrequencies)[0];
- //currentMaxCount keeps track of the number of times the currentMaxKey was in text
- let currentMaxCount = wordFrequencies[currentMaxKey];
- //we loop through each word in our frequencies object and compare its value with the currentMaxCount and change the currentMaxKey if the value is greater than the currentMaxCount. Then we update the currentMaxCount
- for (let word in wordFrequencies) {
- if (wordFrequencies[word] > currentMaxCount) {
- currentMaxKey = word;
- currentMaxCount = wordFrequencies[word];
- }
- }
- //we return the word that comes up the most times
- return currentMaxKey;
- }
Add Comment
Please, Sign In to add comment