Home > Mobile >  How could I make this code more effective - js?
How could I make this code more effective - js?

Time:09-21

function checkValue(val) {
  if (val === 1 || val === 4 || val === 7) {
    return val - 2
  }
  if (val === 2 || val === 5 || val === 8) {
    return val - 1
  }
  if (val === 3 || val === 6 || val === 9) {
    return val
  }
}

console.log(6 - checkValue(6))

how to make this code simple and dynamic to prevent repetitive code writing

CodePudding user response:

function checkValue(val){
  const reminder = val % 3;
  return reminder ? val -  (3 - reminder) : val;
}
  • Related