-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmostCommonWord.js
More file actions
33 lines (27 loc) · 858 Bytes
/
mostCommonWord.js
File metadata and controls
33 lines (27 loc) · 858 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
/**
* @param {string} paragraph
* @param {string[]} banned
* @return {string}
*/
var mostCommonWord = function(paragraph, banned) {
let words = paragraph.toLowerCase().split(/[ ,.!?';]+/);
const wordCount = new Map();
let mostCommon = { value: 0, word: "" };
for (word of words) {
if (banned.includes(word)) {
// do nothing
} else if (wordCount.get(word)) {
wordCount.set(word, wordCount.get(word) + 1);
} else {
wordCount.set(word, 1);
}
if (wordCount.get(word) > mostCommon.value) {
mostCommon = { value: wordCount.get(word), word };
}
}
return mostCommon.word;
};
const paragraph = "Bob hit a ball, the hit BALL flew far after it was hit.";
const banned = ["hit"];
console.log(mostCommonWord(paragraph, banned)); // "ball"
console.log(mostCommonWord("a, a, a, a, b,b,b,c, c", ["a"]));