|
1 | | -/* |
2 | | - Count the number of times a word appears in a given string. |
| 1 | +function countWords(text) { |
| 2 | + if (typeof text !== "string") { |
| 3 | + throw new Error("Input must be a string"); |
| 4 | + } |
3 | 5 |
|
4 | | - Write a function called countWords that |
5 | | - - takes a string as an argument |
6 | | - - returns an object where |
7 | | - - the keys are the words from the string and |
8 | | - - the values are the number of times the word appears in the string |
| 6 | + // remove punctuation and make lowercase |
| 7 | + const cleanedText = text.toLowerCase().replace(/[.,!?]/g, ""); |
9 | 8 |
|
10 | | - Example |
11 | | - If we call countWords like this: |
| 9 | + const words = cleanedText.split(/\s+/); |
12 | 10 |
|
13 | | - countWords("you and me and you") then the target output is { you: 2, and: 2, me: 1 } |
| 11 | + const counts = {}; |
14 | 12 |
|
15 | | - To complete this exercise you should understand |
16 | | - - Strings and string manipulation |
17 | | - - Loops |
18 | | - - Comparison inside if statements |
19 | | - - Setting values on an object |
| 13 | + for (const word of words) { |
| 14 | + if (!word) continue; |
20 | 15 |
|
21 | | -## Advanced challenges |
| 16 | + if (counts[word]) { |
| 17 | + counts[word]++; |
| 18 | + } else { |
| 19 | + counts[word] = 1; |
| 20 | + } |
| 21 | + } |
22 | 22 |
|
23 | | -1. Remove all of the punctuation (e.g. ".", ",", "!", "?") to tidy up the results |
| 23 | + return counts; |
| 24 | +} |
24 | 25 |
|
25 | | -2. Ignore the case of the words to find more unique words. e.g. (A === a, Hello === hello) |
26 | | -
|
27 | | -3. Order the results to find out which word is the most common in the input |
28 | | -*/ |
| 26 | +module.exports = countWords; |
0 commit comments