Skip to content

Commit 978200e

Browse files
authored
Enhance countWords function with input checks
Add input validation and handle empty strings in countWords function.
1 parent 427c69c commit 978200e

1 file changed

Lines changed: 24 additions & 0 deletions

File tree

‎Sprint-2/stretch/count-words.js‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,3 +26,27 @@
2626
2727
3. Order the results to find out which word is the most common in the input
2828
*/
29+
30+
function countWords(str) {
31+
if (typeof str !== "string") {
32+
throw new TypeError("Expected a string as input");
33+
}
34+
35+
// Handle empty or whitespace-only strings
36+
if (str.trim() === "") return {};
37+
38+
const words = str.split(" ");
39+
const counts = {};
40+
41+
for (const word of words) {
42+
if (counts[word]) {
43+
counts[word] += 1;
44+
} else {
45+
counts[word] = 1;
46+
}
47+
}
48+
49+
return counts;
50+
}
51+
52+
module.exports = countWords;

0 commit comments

Comments
 (0)