-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdecoder.js
48 lines (41 loc) · 1.15 KB
/
decoder.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
var _ = require('underscore');
var exec = require('child_process').exec;
var async = require('async');
module.exports = function() {
// searches the file for the given regex string
// and returns an array of matching lines with a 100 result limit
function grep(search, file, callback) {
var command = 'grep -E -m 100 ' + search + ' ' + file;
exec(command, function(stderr, stdout, stdin) {
var results = [];
if(stdout) {
results = stdout.split("\n");
results.pop();
}
callback(results);
});
}
function decodeWord(word, callback) {
if(word.length < 3) {
callback(null, word);
return;
}
var randomResult = '';
var search = '^' + word[0] + '.{' + word.slice(1,-1) + '}' + word[word.length-1] + '$';
grep(search, 'words-list', function(results) {
if(results && results.length > 0)
randomResult = results[Math.floor(Math.random() * results.length)];
callback(null, randomResult);
});
}
return {
decodeSentence: function(sentence, success, fail) {
async.map(sentence.split(' '), decodeWord, function(err, results) {
if(err)
fail(err);
else
success(results.join(' '));
});
}
};
}();