156k views
3 votes
Write the function calcWordFrequencies () in that uses the JavaScript prompt () function to read a list of words (separated by spaces). The function should output those words and their frequencies to the console

Ex: If the prompt input is:
hey hi Mark hi mark
the console output is:
hey 1
hi 2
Mark 1
mark 1
Hint: Place unique words in a map where the key is the word, and the associated value is the word's frequency. To test the JavaScript in your web browser, call the cachordFrequenCies 0 function from the JavaScript console.

User Tyrex
by
7.1k points

1 Answer

3 votes

Final answer:

The calcWordFrequencies function uses JavaScript's prompt() to get input, counts word frequencies with a map, and outputs the results to the console.

Step-by-step explanation:

To write a function calcWordFrequencies that reads a list of words and outputs their frequencies, you would first use the prompt() function in JavaScript to get user input. Then, you would split the input string into words and count the frequency of each word with a map or an object. Here is an example of how to write this function:

function calcWordFrequencies() {
var input = prompt('Enter words separated by spaces:');
var words = input.split(' ');
var frequencyMap = {};

for (var i = 0; i < words.length; i++) {
var word = words[i].toLowerCase();
if (frequencyMap[word]) {
frequencyMap[word]++;
} else {
frequencyMap[word] = 1;
}
}

for (var word in frequencyMap) {
console.log(word + ' ' + frequencyMap[word]);
}
}

// Call the function from the JavaScript console to test
// calcWordFrequencies();

This function iterates over the input words and keeps count of their frequencies in a map. It then logs each word's frequency to the console. Note that it converts all words to lowercase to count them correctly without case sensitivity.

User Jiangzhen
by
8.7k points