-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlibrary.mjs
29 lines (27 loc) · 963 Bytes
/
library.mjs
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
import readline from 'readline';
export const formatAnswer = (answer) => {
let output = answer;
if (Array.isArray(answer)) {
output = output.map(o => (Array.isArray(o) ? o.join(' ') : o.toString()));
output = output.join('\n');
}
return output.toString().trim();
};
export const runFromCli = (fn) => {
const handle = readline.createInterface({ input: process.stdin, output: process.stdout, terminal: false });
let lines = [];
handle.on('line', (line) => {
// Custom indication of input end to also allow manual input and multi inputs, mostly for development testing
if (line === ' ') {
const answer = fn.call(null, lines);
console.log(formatAnswer(answer));
lines = [];
} else {
lines.push(line);
}
});
handle.on('close', () => {
const answer = fn.call(null, lines);
console.log(formatAnswer(answer));
});
};