-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathword_count.js
43 lines (40 loc) · 1.09 KB
/
word_count.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
33
34
35
36
37
38
39
40
41
42
43
var fs = require('fs')
, completedTasks = 0
, tasks = []
, wordCounts = {}
, filesDir = './text';
function checkIfComplete() {
completedTasks++;
if (completedTasks == tasks.length) {
for(var index in wordCounts) {
console.log(index +': ' + wordCounts[index]);
}
}
}
function countWordsInText(text) {
var words = text.toString().toLowerCase().split(/\W+/).sort();
for(var index in words) {
var word = words[index];
if (word) {
wordCounts[word] = (wordCounts[word]) ? wordCounts[word] + 1 : 1;
}
}
}
fs.readdir(filesDir, function(err, files) {
if (err) throw err;
for(var index in files) {
var task = (function(file) {
return function() {
fs.readFile(file, function(err, text) {
if (err) throw err;
countWordsInText(text);
checkIfComplete();
});
}
})(filesDir + '/' + files[index]);
tasks.push(task);
}
for(var task in tasks) {
tasks[task]();
}
});