Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

alter the direction of loop dynamically

I am trying to come up with an algorithm for an "approaching" behavior between two integers. Basically, given two integers, a and b, i want a to "approach" b, even if b is less than a. The way i think this should look is a swapping of the loop incrementer function:

for (var i = a; approachCond(i, a, b); approachDir(i,a, b)) {
   // some fn(a, b);
}

where

approachCond(i, a, b) {
 return a < b ? i < b :  i > b;
}

and

approachDir(i, a, b) {
 return a < b ? i++ : i--
}

However, when i try doing this the browser freezes (Chrome). Does anyone know how to dynamically alter the direction of a loop?

like image 447
dopatraman Avatar asked Jul 29 '15 20:07

dopatraman


1 Answers

I think it's a little clearer to read if you just use a while loop:

'use strict';
let a = 12, b = 6;

let i = a;

while (i !== b) {
  console.log(i);
  i += a < b ? 1 : -1;
}

I even left the cute ternary since people seem so opposed to if-statements these days.

like image 87
Mathletics Avatar answered Oct 07 '22 17:10

Mathletics