0

EDIT : Thanks for the answers. I got the solution to achieve below with Promises. If this can be done without it in a simpler way please answer :)

I need to take standard input like below

3 60
120 30
100 25
30 10

Variable form for above

n W
v1 w1
v2 w2
v3 w3
. .
. .
. .
vn wn

v and w values will be stored in v[ ] and w[ ] arrays

How can I do it using rl.on()?

My code looks like below. I am not sure on how to pass 'n' in question2 while calling it and the code is not working as expected in general because of asynchronous behaviour which I'm not quite clear about. Any best practices on taking multiple numbers in multiple line inputs in NodeJS would be helpful.

    var readline = require('readline');
    var rl = readline.createInterface({
        input: process.stdin,
        output: process.stdout,
        terminal: false
      });
    
      const question1 = () => {
        return new Promise((resolve, reject) => {
          rl.on('line', (line) => {
            const n = line.split(" ")[0];
            const capactity = line.split(" ")[1];
            console.log(n)
            console.log(capactity)
            resolve()
          })
        })
      }
      
      const question2 = n => {
        return new Promise((resolve, reject) => {
        for(var i=0; i<n; i++){
            rl.on('line', (line) => {        
                values.push(line.split(" ")[0]);
                weights.push(line.split(" ")[1]);
                console.log(values);
                console.log(weights);
                resolve()
            })
        }
          
        })
      }
      
      const main = async () => {
        await question1()
        await question2()
        rl.close()
      }
      
      main()
  • Just call `await question()` in a loop? – Bergi Dec 01 '20 at 13:29
  • @Bergi you mean the loop I am using inside question2, I should use it inside main? Also, could you please comment on reusability of 'n'? I have declared it in question1 and need it in question2! – Krisha Engineer Dec 01 '20 at 13:34
  • Oops, I missed that you already have the loop and were just missing the argument. You will need to fulfill the promise returned by question1 with the number, then you can `const n = await question1(); const arr = await question2(n);` – Bergi Dec 01 '20 at 13:37
  • @bergi @krishna - bergi is right, but you also need to change the ```resolve``` on each promise to return a value through the promise model, in quesiton1 it needs to be ```resolve(n)```... – akaphenom Dec 01 '20 at 13:38

1 Answers1

0

You'll need to return the values needed from question1 and pass them as parameters to question2:

I would also try to get rid of any callback pattern when using async-await, so changing the

new Promise((resolve) => {
  rl.on('line', (line) => {
    // calculate
    resolve();
  })
})

to

const line = await new Promise(resolve => rl.on('line', resolve));
// calculate

See below:

const readline = require('readline');
const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout,
    terminal: false
});

const question1 = async () => {
    const line = await new Promise(resolve => rl.on('line', resolve)); 
    const n = line.split(" ")[0];
    const capactity = line.split(" ")[1];
    return { n, capactity };
}

const question2 = async (n) => {
    const values = [];
    const weights = [];
    for(let i = 0; i < n; i++) {
        const line = await new Promise(resolve => rl.on('line', resolve)); 
        values.push(line.split(" ")[0]);
        weights.push(line.split(" ")[1]);
    }

    return { values, weights };
}

const main = async () => {
    const { n, capactity } =  await question1();
    const { weights, values } = await question2(n);
    rl.close();
    console.log(weights, values);
}

main();
andlrc
  • 41,466
  • 13
  • 82
  • 108
  • Thanks!! Just one question about syntax though, const { weights, values } means that it is object of arrays without a name for object? and similarly i earlier came across - const [x, y] - this would be an array without a name? – Krisha Engineer Dec 01 '20 at 14:04
  • @KrishaEngineer It's called destructuring assignment, see mdn: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment – andlrc Dec 01 '20 at 14:35
  • 1
    deleting my answer as this covererd it and is clearer. cheers! – akaphenom Dec 01 '20 at 16:28