JS – find currentClosetTo()

By 27th August 2018Tutourial & Tips

Scenario:
For every minute that passes, we want to find the closest(current minute for example 2) to the closest step_num (e.g. steps of 3).

So for this, if its 2 then its closer to 3.
If its 4 then its still closer to 3.
If its 5 then its not closwer to 6.
etc.
etc.

function currentClosetTo(num, step_num) {
  let a = num / step_num;
  console.log('decimals: '+ a);
  let b = Math.trunc(a);
  console.log('trunc: '+ b);
  let c = a - b;
  console.log('result: '+ c);
  if (c == 0) {
      let xx = num;
      console.log(xx);
    } else if (c < 0.5) {
      let xx = num - 1;
      console.log(xx);
    } else if (c => 0.5) {
      let xx = num + 1;
      console.log(xx);
    }  
}
currentClosetTo(2, 4);