Skip to content

Instantly share code, notes, and snippets.

@lauras12
Created May 20, 2020 15:39
Show Gist options
  • Save lauras12/8827f0060ddfcffdf108c460886440db to your computer and use it in GitHub Desktop.
Save lauras12/8827f0060ddfcffdf108c460886440db to your computer and use it in GitHub Desktop.
Iterating through objects | js-v1 checkpoint
function getTokens(rawString) {
// The 'getTokens' function is definded by the parameter 'rawString'
return rawString.toLowerCase().split(/[ ,!.";:-]+/).filter(Boolean).sort();
}
// 'rawString.toLowerCase()' forces all of the characters in the rawString to lowercase.
// '.split(/[ ,!.";:-]+/)' splits the 'rawString' into a new array using the seperators (/[ ,!.";:-]+/) and where to
// spilt each word.
// '.filter(Boolean)' removes all of the false items from the array.
// '.sort()' sorts all of the items in the array alphabetically.
function mostFrequentWord(text) {
// Declares a function called mostFrequentWord with a parameter of 'text'.
let words = getTokens(text);
// The above declares the variable 'words' and assigns it the value of text that has been run through the getTokens
// function.
let wordFrequencies = {};
// This creates the empty object called 'wordFrequencies'.
for (let i = 0; i <= words.length; i++) {
// The for loop that iterates through each element in the array.
if (words[i] in wordFrequencies) {
wordFrequencies[words[i]]++;
// This if statement states that if the current word in the array is already in the wordFrequencies object, then the // loop increases its value by 1.
} else {
wordFrequencies[words[i]] = 1;
}
// This else statement states that if it is not in the wordFrequencies object, then it adds it and sets it a value of // 1.
}
let currentMaxKey = Object.keys(wordFrequencies)[0];
// The above declares a variable called currentMaxKey with a value that is equal to whatever the first key in the
// wordFrequencies object is.
let currentMaxCount = wordFrequencies[currentMaxKey];
// The above declares a variable called currentMaxCount with a value that is defined with the currentMaxKey variable.
for (let word in wordFrequencies) {
// This loop looks through the keys in the wordFrequencies object.
if (wordFrequencies[word] > currentMaxCount) {
// This if statement compares the keys in the object to their value to the currentMaxCount.
currentMaxKey = word;
currentMaxCount = wordFrequencies[word];
// If the value of the word is greater than currentMaxCount, currentMaxKey replace the word stored in currentMaxKey // and sets the currentMaxCount to its value.
}
}
return currentMaxKey;
// The above will output the word that occurs the most in the string from the method.
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment