Created
May 4, 2018 04:11
-
-
Save ukhlivanov/58cf2b6d5375bd6a4d467d651e36b31c to your computer and use it in GitHub Desktop.
ThinkFul(read code)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function getTokens(rawString) { | |
// Returns array of strings, with lower case, spaces and ,!.";:- - these simbols will be deleted | |
//regardless of how many times they were repeated and will be removed any falsy items from an array | |
// the array will be sorted alphabetically. As a result, an array of words is returned in the alphabetical order. | |
return rawString.toLowerCase().split(/[ ,!.";:-]+/).filter(Boolean).sort(); | |
} | |
function mostFrequentWord(text) { | |
// For the text fragment "text" we form a word array in alphabetical order and save it in the "words" array | |
let words = getTokens(text); | |
//create an object for counting the number of words | |
let wordFrequencies = {}; | |
// It is going to iterate thru the array "words", from index 0 till last index of array | |
// In the condition, it is checked whether there is a current word in wordFrequencies, | |
//if there is, then the counter is updated for this words to + 1, and if not, | |
//then this word with the initial value 1 is added. | |
for (let i = 0; i <= words.length; i++) { | |
if (words[i] in wordFrequencies) { | |
wordFrequencies[words[i]]++; | |
} else { | |
wordFrequencies[words[i]] = 1; | |
} | |
} | |
// In the wordFrequencies object, the key with index 0 has the current maximum number of matches, | |
// This value is saved in variable currentMaxCount | |
let currentMaxKey = Object.keys(wordFrequencies)[0]; | |
let currentMaxCount = wordFrequencies[currentMaxKey]; | |
// It is going to iterate thru all the keys of the wordFrequencies object and check that there are words with | |
//a value greater than our current maximum, if there is then change our current maximum to a new value | |
for (let word in wordFrequencies) { | |
if (wordFrequencies[word] > currentMaxCount) { | |
currentMaxKey = word; | |
currentMaxCount = wordFrequencies[word]; | |
} | |
} | |
// return the word with the maximum number of matches | |
return currentMaxKey; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment