Search code examples
javascriptalgorithmrefactoringmathematical-optimizationmodulo

Return difference between function argument and given number with limited bottom margin


I have this code (JavaScript) here and it seems like I could refactor it in just one instruction, maybe using modulo (%)? (note: n is always between 0 and 6, no need to deal with other cases)

switch (n) {
  case 0: 
    return 1
  case 1:
    return 7
  case 2:
    return 6
  case 3:
    return 5
  case 4:
    return 4
  case 5:
    return 3
  case 6:
    return 2
}

I could do:

if (n === 0) {
  return 1
} 
return (8 - n)

Is there an even shorter way using modulo sign that I could do this?


Solution

  • Here's the modulo version:

    const inputs = [0, 1, 2, 3, 4, 5, 6];
    
    function fn(x) {
      return 7 - ((x + 6) % 7);
    }
    
    console.log(inputs.map(fn))