Home > Back-end >  How to make a function that return an index with a limit
How to make a function that return an index with a limit

Time:05-31

I've wondered how can I optimize the conditions to function that is flexible enough to return an index that has a limitation of 3 index

if(val === 0) return 0;
if (val === -90) return 3;
if (val === -180) return 2;
if (val === -270) return 1;
if (val === -360) return 0;
if (val === -450) return 3;

if(val === 0) return 0;
if (val === 90) return 1;
if (val === 180) return 2;
if (val === 270) return 3;
if (val === 360) return 0;
if (val === 450) return 1;

and so on

I wonder how to make a function that if a user increments by 90 the returns should get incremented with a limit of 3 then after 3 it will return 0 index

CodePudding user response:

function f(x) {
 let z = x / 90;
 let y = z % 4;
 return y < 0 ? 4   y : y;   
}



for(let i =  -90 * 10; i <= 90 * 10; i = i   90) {
 console.log(`x = ${i} => result => ${f(i)}`);
}

function f(x) {
  return ((x / 90) % 4   4) % 4;
}


 for(let i =  -90 * 10; i <= 90 * 10; i = i   90) {
  console.log(`x = ${i} => result => ${f(i)}`);
 }

CodePudding user response:

you should get the minimum input first, then add 360 to it.

val = 360 val;

if(val % 360 === 90){
    return 1
}
if(val % 360 === 180){
    return 2
}
if(val % 360 === 270){
    return 3
}
if(val % 360 === 0){
    return 0
}

CodePudding user response:

You can try dividing by 90 for the positive numbers and for the negative numbers add 360 first then divide by 90.

CodePudding user response:

You can do (val % 360) / 90

if (val % 90 !== 0) return null.

return (val % 360) / 90;

CodePudding user response:

Try

const f = v => (v = v / 90 % 4, v < 0 ? 4   v : v | 0);

for (let i = -450; i <= 450; i  = 90) {
 console.log(`f(${i}) = ${f(i)}`);
}

  • Related