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();
- }
- // The getTokens function is first asking for an input of a string(rawString).
- // Then from the many different methods it alters the string in these ways:
- // 1) lower case strings
- // 2) It turns the string into an array that creates a new substring when /[ ,!.";:-]+/ is present.
- // 3) It also only returns True statements.
- // 4) Lastly it sorts the array alphabetically.
- function mostFrequentWord(text) {
- let words = getTokens(text);
- // It sets the variable "words" with a value of a string from getTokens.
- let wordFrequencies = {};
- // wordFrequencies" variable is set as an empty object in which a number will be stored.
- for (let i = 0; i <= words.length; i++) {
- if (words[i] in wordFrequencies) {
- wordFrequencies[words[i]]++;
- } else {
- wordFrequencies[words[i]] = 1;
- }
- // In this loop it states that if a word appears in the object, then the count is increased, and if it does not appear, then it's value is 1."
- }
- let currentMaxKey = Object.keys(wordFrequencies)[0];
- let currentMaxCount = wordFrequencies[currentMaxKey];
- // The variable "currentMaxKey" that sets the key at 0 and "currentMaxCount" is a variable that gives the value shows up in the object.
- for (let word in wordFrequencies) {
- if (wordFrequencies[word] > currentMaxCount) {
- currentMaxKey = word;
- currentMaxCount = wordFrequencies[word];
- }
- // This loop means that that if the word count is larger than value of the currentMaxCount, then the values change to reflect the "wordFrequencies" .
- }
- return currentMaxKey;
- // This returns the word with the highest number.
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement