Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function getTokens(rawString) {
- //BB: This function returns a sorted array of all words in 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); // BB: get sorted array of all words in 'text'
- let wordFrequencies = {}; // BB: init object -- list of keys (words) and frequencies
- // BB: loop through each word
- // if word not already a key,
- // add the key and set its value to 1,
- // otherwise increment its value by 1
- for (let i = 0; i <= words.length; i++) {
- if (words[i] in wordFrequencies) {
- wordFrequencies[words[i]]++;
- } else {
- wordFrequencies[words[i]] = 1;
- }
- }
- // BB: init "most frequent word/key" and count vars:
- let currentMaxKey = Object.keys(wordFrequencies)[0];
- let currentMaxCount = wordFrequencies[currentMaxKey];
- // BB: for each key in wordFrequencies, compare its count
- // to the max count, and if it's greater, set the
- // MaxKey and MaxCount to this Key and Count
- for (let word in wordFrequencies) {
- if (wordFrequencies[word] > currentMaxCount) {
- currentMaxKey = word;
- currentMaxCount = wordFrequencies[word];
- }
- }
- // BB: return the result of the MaxKey
- // (word with greatest frequency)
- return currentMaxKey;
- }
Add Comment
Please, Sign In to add comment