Reputation: 302
Use: Node.js 8.x
Purpose: Reading standard input and storing it in an array
Error: the Last Line doesn't save in array.
what is my misunderstanding about javascript? async and sync?
const promise = require('promise')
, readline = require('readline');
const stdRl = readline.createInterface({
input: process.stdin,
output: process.stdout,
terminal: false
});
GLOBAL_COUNTER_READLINE = 0;
GLOBAL_MAPSIZE = 0;
GLOBAL_MAPDATA = [];
stdRl.on('line', (input) => {
// first line : setMapSize
// second line ~ GLOBAL_MAPSIZE : appendMapDataRow
// GLOBAL_MAPSIZE + 1 line : getMapData, countChar
if (GLOBAL_COUNTER_READLINE == 0) {
// setMapSize;
GLOBAL_MAPSIZE = input;
console.log(`Map Size is : ${GLOBAL_MAPSIZE}`);
} else if (GLOBAL_COUNTER_READLINE != GLOBAL_MAPSIZE) {
// appendMapDataRow
GLOBAL_MAPDATA.push(input);
} else if(GLOBAL_COUNTER_READLINE == GLOBAL_MAPSIZE){
//getMapData
for (var row = 0; row < GLOBAL_MAPDATA.length; row++) {
console.log(`${GLOBAL_MAPDATA[row]}`);
}
stdRl.close();
}
GLOBAL_COUNTER_READLINE++;
});
javascript is awesome, but it's hard to me.
Upvotes: 2
Views: 295
Reputation: 35491
Your main issue is that, since the number of lines is the first value you read, you shouldn't actually increment the counter for it. You should start incrementing once you actually receive the first line of data.
if (GLOBAL_MAPSIZE == 0) {
GLOBAL_MAPSIZE = input;
console.log(`Map Size is : ${GLOBAL_MAPSIZE}`);
} else if (GLOBAL_COUNTER_READLINE < GLOBAL_MAPSIZE) {
GLOBAL_MAPDATA.push(input);
GLOBAL_COUNTER_READLINE++; // <-- move the increment here
} else {
for (var row = 0; row < GLOBAL_MAPDATA.length; row++) {
console.log(`${GLOBAL_MAPDATA[row]}`);
}
stdRl.close();
}
Another potential future issue is that you're instantiating objects but using them as primitive values.
Two instances of Number
are never equal:
console.log(
new Number(0) == new Number(0) // false
)
Because objects are compared by referential equality (basically checking if they are the same instance; if they refer to the same object in memory).
You could compare their values:
console.log(
new Number(0).valueOf() == new Number(0).valueOf() // true
)
But it's much simpler to just use the raw primitive.
console.log(
0 == 0 // true
)
So in your code:
GLOBAL_COUNTER_READLINE = 0;
GLOBAL_MAPSIZE = 0;
GLOBAL_MAPDATA = [];
Upvotes: 3