Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // The getTokens function is a filtering function with the arguement rawstring. It will return an array
- of lowercase data elements that splits on a sequence of one or more commas or whitespace so that it will not
- produce empty elements in the results. This function serves to perform the matching of a pattern or a
- search and replace.//
- function getTokens(rawString) {
- // NB: `.filter(Boolean)` removes any falsy items from an array //This will remove any null, 0, or Nan value from the array or string//
- return rawString.toLowerCase().split(/[ ,!.";:-]+/).filter(Boolean).sort(); // .sort function sorts array by alphabetical order//
- }
- //The mostFrequentWord function assigns when called the getTokens array to the variable words.
- Below that is a new object for word frequency count called wordFrequencies. A for loop that will run and reference
- what "i" is which is the first text in the string that will return. They start at 0 not 1 and if the
- condition of less than or equal to words.length the value will be incremented and run immediately.
- //
- function mostFrequentWord(text) {
- let words = getTokens(text);
- let wordFrequencies = {};
- for (let i = 0; i <= words.length; i++) {
- if (words[i] in wordFrequencies) {
- wordFrequencies[words[i]]++;
- } else {
- wordFrequencies[words[i]] = 1;
- }
- }
- let currentMaxKey = Object.keys(wordFrequencies)[0];
- let currentMaxCount = wordFrequencies[currentMaxKey];
- for (let word in wordFrequencies) {
- if (wordFrequencies[word] > currentMaxCount) {
- currentMaxKey = word;
- currentMaxCount = wordFrequencies[word];
- }
- }
- return currentMaxKey;
- }
- // The script wil return the currentMaxKey and we will have the word used most.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement