Search code examples
javascriptnode.jsprocessstdin

How to pass in process.stdin as Javascript with Node?


I'm writing a poker game in Javascript that's supposed to take stdin as follows:

enter image description here

The first line of input will contain a single integer representing the number of players. This number will always be greater than 0 and less than 8.

The following n lines, where n is the number of players, will contain a single integer representing the id of the player, followed by three space-separated cards representing a hand belonging to a player.

The output, printed to stdout, will be the ID of the winning player.

enter image description here

But my function is in Javascript so... how do I convert this stdin to say an integer and an object like so:

function playPoker(n, cardsDealt){
  // functionality
}

const num = 3;
const hands = {
  '0': ['4c,', '5c', '6c'],
  '1': ['Kd', '5d,', '6d'],
  '2': ['Jc', 'Qd,', 'Ks'],
}
playPoker(num, hands);

I got as far as playing around with process.stdin like so but not sure how to interpret the input as Javascript:

enter image description here


Solution

  • Pass the incoming integer to your playPoker function then use the count to loop through your hand generation logic, save it to an array, pass the array back, and use it to generate a formatted string and determine your winner.

    const playPoker = num => {
      let i = 1;
      let hands = [];
    
      if (!isNan(parseInt(num))) {
        while (i <= parseInt(num)) {
          let hand = [];
          // generate your hand
          hands.push(hand);
          i++;
        } 
    
        return hands;
      } else {
        return 'Not a valid number';
      }
    }
    
    process.stdin.on('data', data => {
      const hands = playPoker(data);
      const handsOut = hands.map(h => `${hands.indexOf(h)}: ${h[0]} ${h[1]} ${h[2]}`);
      process.stdout.write(handsOut.toString().replace(',', '\n'));
    
      let winner;
      // decide winner
      process.stdout.write(winner);
    });