-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
55 lines (50 loc) · 1.24 KB
/
index.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
44
45
46
47
48
49
50
51
52
53
54
55
'use strict'
var _ = require('lodash');
var async = require('async');
module.exports = function(input) {
var strings = [];
var dictionary = [];
// convert string input to array
Array.isArray(input) ? strings = input : strings.push(input.toString());
async.each(strings, function(string, callback) {
var total;
var i = 0;
string = string.toString();
var words = string
.replace(/[.,?!;:()“”"'\-0123456789]/g, " ")
.replace(/[\u2026]/g, " ") //ellipsis
.replace(/\s+/g, " ")
.toLowerCase()
.split(" ");
total = words.length;
_(words).forEach(function (w) {
i++;
var entry = _.find(dictionary, { 'word': w });
if (entry != undefined) {
entry.count = entry.count+1;
}else{
dictionary.push({ 'word': w, 'count': 1 });
}
if (i === total) { callback(); } // all words processed
});
}, function(err){
if( err ) {
console.log('An error occured, exiting.');
process.exit();
} else {
// remove possible blank entry from array
_.remove(dictionary, function(e) {
if (e.word === '') {
return true;
}else{
return false;
}
});
// reorder dictionary by count
dictionary = _.sortBy(dictionary, function(e) {
return e.count*-1;
});
}
});
return dictionary;
}