-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
131 lines (117 loc) · 2.52 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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
/* jslint esversion: 6 */
const cin = process.stdin;
const cout = process.stdout;
const fnList = {
prompt: pprompt,
confirm: pconfirm,
multiline: pmultiline
};
// Public functions
function ask(questions) {
"use strict";
let answers = {};
let i = 0;
return new Promise(function(resolve, reject) {
function askQuestion(item) {
let key = item.key;
let msg = item.msg;
let fn = fnList[item.fn];
if (!key) {
throw new Error('A value for `key` must be defined for question '+i);
}
if (!msg) {
throw new Error('A value for `msg` must be defined for question '+i);
}
if (!fn) {
throw new Error('A value for `fn` must be "prompt", "confirm", or "multiline" for question '+i);
}
if (fn) {
fn(msg, key, answers).then(
function() {
next();
}
);
}
}
function next() {
if (i < questions.length) {
var question = questions[i];
i++;
askQuestion(question);
}
else {
resolve(answers);
}
}
next();
});
}
function prompt(msg, multiLine){
"use strict";
return new Promise(function(resolve) {
cout.write(msg);
cin.setEncoding('utf8');
if (multiLine) {
let buf = [];
cout.write('\n');
cin.on('data',
function(val){
if ('\n' == val || '\r\n' == val) {
cin.pause();
cin.removeAllListeners('data');
resolve(buf.join('\n'));
buf = null;
} else {
buf.push(val.slice(0,-1));
}
}
).resume();
}
else {
cin.once('data',
function(val){
cin.pause();
resolve(val.slice(0,-1));
}
).resume();
}
});
}
function confirm(msg) {
"use strict";
return prompt(msg, false).then(
function(val) {
return(/^y|yes|ok|true$/i.test(val));
}
);
}
function multiline(msg) {
"use strict";
return prompt(msg, true);
}
// Private functions
function promiseFn(msg, key, answers, fn) {
"use strict";
answers = answers || {};
return fn(msg).then(
function(resp) {
answers[key] = resp;
return answers;
}
);
}
function pprompt(msg, key, answers) {
return promiseFn(msg, key, answers, prompt);
}
function pconfirm(msg, key, answers) {
return promiseFn(msg, key, answers, confirm);
}
function pmultiline(msg, key, answers) {
return promiseFn(msg, key, answers, multiline);
}
module.exports = {
ask,
confirm,
multiline,
prompt
};