-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnumberOfWordOccur.js
executable file
·33 lines (24 loc) · 1.04 KB
/
numberOfWordOccur.js
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
// You need to write a method that counts the number of occurences
// of a word in a given text.
// The word counter is created as follows:
// var sample = "Lorem ipsum";
// var counter = wordCounter(text);
// Then one can get the count for a given word like this:
// console.log(counter.count("Lorem")); // 1
// console.log(counter.count("hey")); // 0
// The input texts are simple: they only contain ASCII characters,
// words are either separate by white spaces or punctuation
// (only , and .). If the input only contain punctuation or white
// spaces, it should return a count of 0 for all words.
// For performance reasons, your implementations should count
// the words once and not parse the text each time the count
// method is called.
var wordCounter = function(text) {
var words = text.match(/[a-z']+/gi) || []
var counts = {};
for (var word of words){
counts['_' + word] = (counts['_' + word] || 0) + 1;
}
return { count: word => counts['_' + word] || 0 }
};
wordCounter("Hello friend .., zzzz hows it going:");