forked from iceddev/your-first-npm-module
-
Notifications
You must be signed in to change notification settings - Fork 0
/
question.js
65 lines (54 loc) · 1.54 KB
/
question.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
56
57
58
59
60
61
62
63
64
65
var readline = require('readline');
var when = require('when');
var solution = require('./solution');
var attempt = require('./attempt');
var successMessage = '{blue}{bold}Challenge Completed{/bold}{/blue}';
var failureMessage = '{red}{bold}Try Again{/bold}{/red}';
function question(text, expectedCmd, success){
var rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.on('SIGINT', function() {
rl.question('Are you sure you want to exit (y/N)? ', function(answer) {
if(answer.match(/^y(es)?$/i)){
rl.close();
} else {
console.log(text);
rl.prompt();
}
});
});
var defer = when.defer();
var expected = when.resolve();
if(typeof expectedCmd === 'string'){
expected = solution(expectedCmd);
} else {
success = expectedCmd;
}
success = success || function(data){
if(typeof data[0] === 'string' && typeof data[1] === 'string'){
return data[0].replace(/\s/g, '') === data[1].replace(/\s/g, '');
} else {
return data[0] === data[1];
}
};
console.log(text);
rl.prompt();
rl.once('line', function(cmd){
rl.close();
when.join(attempt(cmd), expected)
.then(success)
.then(function(passed){
if(passed){
console.log(successMessage);
defer.resolve();
} else {
console.log(failureMessage);
when(question(text, expectedCmd, success), defer.resolve);
}
}, console.error.bind(console));
});
return defer.promise;
}
module.exports = question;