Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //function that takes an argument rawString and returns a sorted array of strings
- function getTokens(rawString) {
- // NB: `.filter(Boolean)` removes any falsy items from an array
- //.toLowerCase() returns the lower case value of rawString
- //.split(/[ ,!.";:-]+/) splits the string into an array of substrings and a regular expression is used as the separator to separate the words of the string at any of the characters in the regex
- //now rawString is an array and .filter() method is used to create a new array with elements that pass the function Boolean which removes all falsy elements
- //then finally the .sort() method is used on the new array and sorts the array of strings by alphabetical order
- //a sorted array of strings with no falsy elements is returned by this function
- return rawString.toLowerCase().split(/[ ,!.";:-]+/).filter(Boolean).sort();
- }
- //function that takes an argument text and returns the updated most frequent word
- function mostFrequentWord(text) {
- //declares a variable called words and sets its value to the returned value of the function getTokens
- let words = getTokens(text);
- //declares a variable called wordFrequencies and sets its value to an empty object
- let wordFrequencies = {};
- //a for loop is used to iterate through the array returned by getTokens(text)
- for (let i = 0; i <= words.length; i++) {
- //starting at index 0, if the element matches some key in wordFrequencies, then it will increment by one to the value of the key
- if (words[i] in wordFrequencies) {
- wordFrequencies[words[i]]++;
- }
- //else if the element does not match some key in wordFrequencies, then the element at words[i] will be added as a new key into wordFrequencies and its value will be set to 1
- else {
- wordFrequencies[words[i]] = 1;
- }
- }
- //declares a variable called currentMaxKey and sets its value to the key at index [0]
- let currentMaxKey = Object.keys(wordFrequencies)[0];
- //declares a variable called currentMaxCount and sets its value to the value of the key wordFrequencies[currentMaxKey]
- let currentMaxCount = wordFrequencies[currentMaxKey];
- //a for in loop that iterates through the keys in wordFrequencies
- for (let word in wordFrequencies) {
- //starting at the first key, if the value at wordFrequencies[word] is greater than the value at currentMaxCount, then currentMaxKey is set to word and the value at currentMaxCount is updated to the value at wordFrequencies[word]
- if (wordFrequencies[word] > currentMaxCount) {
- currentMaxKey = word;
- currentMaxCount = wordFrequencies[word];
- }
- }
- //the function should return the key with the highest value/count
- return currentMaxKey;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement