Skip to content

Commit 0b22c9f

Browse files
author
Enice-Codes
committed
Complete count-words project
1 parent 5a9c557 commit 0b22c9f

2 files changed

Lines changed: 31 additions & 28 deletions

File tree

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

Lines changed: 14 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -1,28 +1,14 @@
1-
/*
2-
Count the number of times a word appears in a given string.
3-
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
9-
10-
Example
11-
If we call countWords like this:
12-
13-
countWords("you and me and you") then the target output is { you: 2, and: 2, me: 1 }
14-
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
20-
21-
## Advanced challenges
22-
23-
1. Remove all of the punctuation (e.g. ".", ",", "!", "?") to tidy up the results
24-
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-
*/
1+
function countWords(str) {
2+
const wordCount = {};
3+
const words = str
4+
.toLowerCase()
5+
.replace(/[^\w\s]/g, "")
6+
.split(/\s+/)
7+
.filter(Boolean);
8+
for (const word of words) {
9+
wordCount[word] = (wordCount[word] || 0) + 1;
10+
}
11+
return wordCount;
12+
}
13+
14+
module.exports = countWords;
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
const countWords = require("./count-words");
2+
3+
test("counts word occurrences in a string", () => {
4+
expect(countWords("you and me and you")).toEqual({ you: 2, and: 2, me: 1 });
5+
});
6+
7+
test("returns an empty object for an empty string", () => {
8+
expect(countWords("")).toEqual({});
9+
});
10+
11+
test("ignores punctuation", () => {
12+
expect(countWords("Hello, world! Hello?")).toEqual({ hello: 2, world: 1 });
13+
});
14+
15+
test("ignores case", () => {
16+
expect(countWords("A a Hello hello")).toEqual({ a: 2, hello: 2 });
17+
});

0 commit comments

Comments
 (0)