Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // takes a string as input and returns an array of all words in the string, stripping non-alphanumeric characters
- function getTokens(rawString) {
- // NB: `.filter(Boolean)` removes any falsy items from an array
- return rawString.toLowerCase().split(/[ ,!.";:-]+/).filter(Boolean).sort();
- }
- // takes in a string of text, and returns a string representation of the most frequently occuring word in that string
- function mostFrequentWord(text) {
- // assigns variable referring to array of words in string
- let words = getTokens(text);
- // declares an empty obj to store word counts
- let wordFrequencies = {};
- // iterates over words in array. for each word, if the word is present in the frequency object, the value is incremented; otherwise
- // it adds the word as a key with a value of 1
- for (let i = 0; i <= words.length; i++) {
- if (words[i] in wordFrequencies) {
- wordFrequencies[words[i]]++;
- } else {
- wordFrequencies[words[i]] = 1;
- }
- }
- // declares variables to track the highest frequency word; intially set to the first key in the array of the frequency object's keys
- let currentMaxKey = Object.keys(wordFrequencies)[0];
- let currentMaxCount = wordFrequencies[currentMaxKey];
- // iterates over keys in wordFrequencies object. if the value (count) of that key is greater than the current max, the key
- // replaces the currentMaxKey, and the value replaces the currentMaxCount
- for (let word in wordFrequencies) {
- if (wordFrequencies[word] > currentMaxCount) {
- currentMaxKey = word;
- currentMaxCount = wordFrequencies[word];
- }
- }
- // You wanted a word!? Well, here's a word! The most frequent word! The best word!
- return currentMaxKey;
- }
Add Comment
Please, Sign In to add comment