[Risolto] Count Words with Maps - JavaScript task

  

3
Argomento iniziale

You are tasked to count the number of words in a text using a Map, any combination of letters, digits and _ (underscore) should be counted as a word. The words should be stored in a Map - the key being the word and the value being the amount of times the word is contained in the text. The matching should be case insensitive. Print the words in a sorted order.

The input comes as an array of strings containing one entry - the text whose words should be counted. The text may consist of more than one sentence.

Examples:

Input:
Far too slow, you're far too slow.

Output:
'far' -> 2 times
're' -> 1 times
'slow' -> 2 times
'too' -> 2 times
'you' -> 1 times


Input:
JS devs use Node.js for server-side JS. JS devs use JS. -- JS for devs --

Output:
'devs' -> 3 times
'for' -> 2 times
'js' -> 6 times
'node' -> 1 times
'server' -> 1 times
'side' -> 1 times
'use' -> 2 times


The output should be printed on the console - print each word in the map in the format "'<word>' -> <count> times", each on a new line.

1 risposta
2

Here is my JS solution:

function countWordsWithMaps(inputLines) {
    let words = inputLines.join('\n').toLowerCase()
        .split(/[^A-Za-z0-9_]+/).filter(w => w != '');
    let wordsCount = new Map();
    for (let w of words)
        wordsCount.has(w) ? wordsCount.set(w,
            wordsCount.get(w) + 1) : wordsCount.set(w, 1);
    let allWords = Array.from(wordsCount.keys()).sort();
    allWords.forEach(w =>
        console.log(`'${w}' -> ${wordsCount.get(w)} times`));
}
 
//countWordsWithMaps([
//    "Far too slow, you're far too slow."
//]);
 
countWordsWithMaps([
    "JS devs use Node.js for server-side JS. JS devs use JS. -- JS for devs --"
]);
Condividi: