Advertisement
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(); // Normalizes input through removing and seperating by spaces/punctuation. Makes it lowercase, sorts it in alphabetical order, and filters out any falsy entries. Finally returns an array of strings.
- }
- function mostFrequentWord(text) {
- let words = getTokens(text); // calls the getTokens function and sets words to the output
- let wordFrequencies = {}; // Object declared outside of for loop to be used later
- for (let i = 0; i <= words.length; i++) {
- if (words[i] in wordFrequencies) { // if current array item is already entered in the object, then add +1 to the count
- wordFrequencies[words[i]]++;
- } else {
- wordFrequencies[words[i]] = 1; // otherwise, make a new word entry and mark it as appearing once
- }
- }
- /*
- Currently, we should have an object that looks like this:
- wordFrequencies = {
- hello: 3,
- thanks: 1,
- goodbye: 2
- }
- */
- let currentMaxKey = Object.keys(wordFrequencies)[0]; // Sets first key to be considered the most frequently used word (however may not be the case)
- let currentMaxCount = wordFrequencies[currentMaxKey]; // Gets the frequency of the word
- for (let word in wordFrequencies) { // For every word in wordFrequency, do this:
- if (wordFrequencies[word] > currentMaxCount) { // If the word we're currently looking at has a larger frequency count than our previously set word, set it to the current one
- currentMaxKey = word;
- currentMaxCount = wordFrequencies[word];
- }
- // this happens all the way through the array until we get the final result: the most frequently used word
- }
- return currentMaxKey; // return the most frequently used word
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement