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) {
- let words = getTokens(text); // get an array words, split based on the regex, lowercase them for ease of comparison, removed boolean values
- let wordFrequencies = {}; //create an object to hold the words
- for (let i = 0; i <= words.length; i++) { //iterate over the word array
- if (words[i] in wordFrequencies) {
- wordFrequencies[words[i]]++; //if the word has has already been added to the object, add 1 to its count
- } else {
- wordFrequencies[words[i]] = 1; // this word isnt in the object yet so add it and set its count to 1
- }
- }
- let currentMaxKey = Object.keys(wordFrequencies)[0]; //to start somewhere, lets set our max word to the first word in keys of object
- let currentMaxCount = wordFrequencies[currentMaxKey]; // same thing here but setting to the count of our first key
- for (let word in wordFrequencies) { //iterate over our word object
- if (wordFrequencies[word] > currentMaxCount) { //now we compare if the current word we are looking at has a higher count than whatever currentMaxCount is set to
- currentMaxKey = word; //if we are here it means we have a new high count so set our current high word to max
- currentMaxCount = wordFrequencies[word]; //same thing here but with the count value of our new high word
- }
- }
- return currentMaxKey; //now that weve run through the entire object we know what our highest count word is so return it
- }
Add Comment
Please, Sign In to add comment