5

The code is simple, I'm very new to programming. You put in the points you need and the result of the game and the output is the minutes of gameplay needed for the points.

It works, my question is how should I convert the output to be in an HH:MM format? I tried if/else cycles, but it's a lot of work, not to mention it's very primitive and hardcoded. Are for cycles the answer? Should I start from the beginning altogether?

Thank you in advance!

function passPoints(input) {
    let gameResult = String(input[0]);
    let pointsNeeded = Number(input[1]);

    let pointsPerMinute = 0;

    if (gameResult == 'w') {
        pointsPerMinute = 6;
    } else if (gameResult == 'l') {
        pointsPerMinute = 4;
    }

    let minutesOfGameplayNeeded = pointsNeeded / pointsPerMinute;


    console.log(minutesOfGameplayNeeded)
}
Larsen
  • 53
  • 3

1 Answers1

3

Here's how I would approach it. Using modulus and dividing by 60 to get the h:m

// as a helper function
const getTimeReadout = m => {
  let a = [Math.floor(m / 60), Math.floor(m % 60)]
  return a.map(t => ('0' + t).slice(-2)).join(':')
}

Here it is integrated into your code:

function passPoints(input) {
  let gameResult = String(input[0]);
  let pointsNeeded = Number(input[1]);

  let pointsPerMinute = 0;

  if (gameResult == 'w') {
    pointsPerMinute = 6;
  } else if (gameResult == 'l') {
    pointsPerMinute = 4;
  }

  let m = pointsNeeded / pointsPerMinute
  let minutesOfGameplayNeeded = [Math.floor(m / 60), Math.floor(m % 60)];
  // now it's in an array so we can iterate it below (adding the zero if needed)
  minutesOfGameplayNeeded = minutesOfGameplayNeeded.map(t => ('0' + t).slice(-2)).join(':')

  console.log(minutesOfGameplayNeeded)
}

passPoints(['w', 427]);

Same thing, but I optimized your code a bit:

function passPoints(input) {
  [gameResult, pointsNeeded] = input
  let pointsPerMinute = gameResult == 'w' ? 6 : gameResult == 'l' ? 4 : 0;
  let m = pointsNeeded / +pointsPerMinute;
  return [Math.floor(m / 60), Math.floor(m % 60)].map(t => ('0' + t).slice(-2)).join(':')
}
console.log(passPoints(['w', 427]));
Kinglish
  • 23,358
  • 3
  • 22
  • 43
  • This is great, however embarrassingly enough I'm failing to incorporate it into my code. Could you please explain how I should do it, I'm a beginner and I'm not studying javascript in English, so I sometimes get confused on the terminology. – Larsen Apr 21 '22 at 19:36
  • 1
    I updated my answer with a couple examples – Kinglish Apr 21 '22 at 20:02