Change cycle direction dynamically

I am trying to find an algorithm for the “approaching” behavior between two integers. Basically, given the two integers a and b , I want a “approach” b , even if b less than a . I think this should look like this is a replacement for the loop increment 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 to do this, the browser freezes (Chrome). Does anyone know how to dynamically change the direction of the loop?

+4
source share
5 answers

Your browser freezes because you are not changing the correct i . You control only i located in the approachDir function. If you return it and set for scope i new value, it will work.

Try:

 for (var i = a; approachCond(i, a, b); i = approachDir(i,a, b)) { // some fn(a, b); } approachDir(i, a, b) { return a < b ? i + 1 : i - 1 } 
+2
source

The problem is approachDir . i++ and i-- are post -increment and post -decrement. This means that they update the variable after they return their original value. Thus, the function returns the original value, not the updated one. To update a variable before returning, you must use ++i or --i .

But you do not need to use the increment operator at all, since the local variable disappears immediately. Just return the new value.

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

You also need to reassign the variable in the loop:

 for (var i = a; approachCond(i, a, b); i = approachDir(i, a, b)) { ... } 

As you wrote the code, you assumed that the variables are passed by reference, not by value, so that the function increment will change the calling variable.

+1
source

I think reading is a little easier if you just use the while :

 'use strict'; let a = 12, b = 6; let i = a; while (i !== b) { console.log(i); i += a < b ? 1 : -1; } 

I even left a sweet triple, as people seem so nasty if-statements these days.

+1
source

It seems that you are too embarrassed by something that is not so difficult. You can simply set the step to positive or negative. eg.

 var a = 20; var b = 5; for (var step = a > b ? -1 : +1; a != b; a += step) { console.log(a); } 
+1
source

One option is to modify approachDir to return a positive or negative value based on if a>b . The average statement may include || and work anyway.

 function approachDir(a, b){ return a>b?-1:1; } var a=3; var b=1; for (var i = a; i<b||i>b; i+=approachDir(a, b)) { console.log(i); } a=1; b=3; for (var i = a; i<b||i>b; i+=approachDir(a, b)) { console.log(i); } 
0
source

All Articles