I'm doing a programming challenge right now but I'm struggling with getting the input right. There is no feedback on my output, only "error" which makes it really hard to debug for me. Here is the input:
4 2
1 4
2 9
4 7
5 8
and I want to collect it like this:
[4, 2, 1, 4, 2, 9, 4, 7, 5, 8];
The test environment tells me to work with the input like this:
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.on('line', (line) => {
var nums = line.split(' ');
/*Solve the test case and output the answer*/
});
How ever I must be getting the wrong array for my nums variable.I tried a bunch of approaches (splitting by /n and whitespaces, iterating with for loop and push... working with rl.close...) but as there is virtually no feedback on my input I am getting kind of desperate here. A simple interface which tells me my program output would help...
SOLUTION
var nums = [];
rl.on("line", line => {
let newLine = line.split(" ");
newLine.map(line => nums.push(line));
});
rl.on("close", function() {
console.log(nums)
});
It was possible for me to debug via the terminal once I got the input right.
The 'line'
event would be emitted every time when rl
read a new line, so you should just declare your nums
outside of the callback function of the listener. Something like this:
...
var sums = [];
rl.on('line', (line) => {
let newNumbers = line.split(' '); // [4, 2]
sums.concat(newNumbers);
});
...
You may want to understand how event emitter and event listener work in JavaScript.
I think there is nothing for you even you register an 'error'
event listener because everything is working as expected. And I believe there must be an event like 'end'
or 'closed'
which would be emitted after rl
read all content of the input, and you can console.log
your sums
array there, I believe you can get your expected result.
You shouldn't handle the sums
array right after the closing brackets, JavaScript is asynchronous, so those codes would be executed before all of the lines are read. If there is a method like rl.close
you should call it in the situation like:
rl.on('line', (line) => {
...
if (line === undefined) { // or any terminal character which createInterface would return.
rl.close();
}
});
And I believe rl.close()
will emit the event like what I said above , something like 'end'
or 'closed'
, put the code to handle the final sums
there.