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();
- }
- //Changing the string to all lower-case, putting spaces(?) between common possible symbols and characters, then filters by Boolean items only (so no symbols), then sorts alphabetically and returns it. //
- function mostFrequentWord(text) {
- //Pulls array/items from above?
- let words = getTokens(text);
- let wordFrequencies = {};
- //Makes an object called wordFrequencies, then starts building a loop that goes over the array from getTokens
- for (let i = 0; i <= words.length; i++) {
- if (words[i] in wordFrequencies) {
- wordFrequencies[words[i]]++;
- } else {
- wordFrequencies[words[i]] = 1;
- }
- //If a word in wordFrequencies appears more than once, ups value of word[i] by one. If hasn’t seen before, logs it as word[i]=1
- }
- let currentMaxKey = Object.keys(wordFrequencies)[0];
- //Makes array called currentMaxKey, made of keys from wordFrequencies.
- let currentMaxCount = wordFrequencies[currentMaxKey];
- //Makes an obj currentMaxCount is contains the most common key and the number of times it appears
- for (let word in wordFrequencies) {
- if (wordFrequencies[word] > currentMaxCount) {
- currentMaxKey = word;
- currentMaxCount = wordFrequencies[word];
- }
- //Makes a loop that checks if a word in wordFrequencies appears more than the currentMaxCount. If so, changes that word key and its frequency to the new currentMaxCount. The word then becomes the currentMaxKey.
- }
- return currentMaxKey;
- //Displays most common word in the text
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement