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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With