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();
- }
- // This is the function declaration (mostFrequentWord) with a single argument (text). It is this function that will detect the most frequent word in a body of text.
- function mostFrequentWord(text) {
- // This is a variable declaration (words) that is assigned to a function (getTokens(text) with the same argument (text) as the parent function.
- var words = getTokens(text);
- // This variable declaration (wordFrequencies) is assigned to an empty object.
- var wordFrequencies = {};
- // This is a for loop which will go through each item in an array (words is an array.)
- for (var i = 0; i <= words.length; i++) {
- // This is a Boolean checking if there is any text in the variable, words, in the object, wordFrequencies.
- if (words[i] in wordFrequencies) {
- // If true, this statement will check the entire object to see how many times this text appears in it (wordFrequencies).
- wordFrequencies[words[i]]++;
- }
- // If false, this statement equates the object to the value of 1.
- else {
- wordFrequencies[words[i]]=1;
- }
- }
- // This variable is assigned to the keys of values of the object (wordFrequencies) of the first item in the array.
- var currentMaxKey = Object.keys(wordFrequencies)[0];
- // This variable is assigned to the
- var currentMaxCount = wordFrequencies[currentMaxKey];
- for (var word in wordFrequencies) {
- if (wordFrequencies[word] > currentMaxCount) {
- currentMaxKey = word;
- currentMaxCount = wordFrequencies[word];
- }
- }
- return currentMaxKey;
- }
Add Comment
Please, Sign In to add comment