The number of cycles to 100 and back to 0 and to 100 again and so on

I must admit that I am not a mathematical expert, so I cannot solve the following problem until I am satisfied.

I have a number, let's say I = 0. I have a function that increments me on each call by 1, and then calls itself again, incrementing at another time, and another and another ... When 100 is reached, I want so that it counts back to 0, and then again, sort of like a tip loop, and I go up and down like an elevator. What is an elegant solution for this?

My decision:

var countingUp = true; var i = 0; function count() { if(i < 100 && countingUp) {i+=1} if(i > 1 && !countingUp) {i-=1} if(i===100) {countingUp=false;} if(i===1) {countingUp=true;} count() } count() 

I am looking for something shorter.

+6
source share
4 answers

It looks good, but is likely to sell your dog into slavery and steal your beer:

 var direction = 1; var i = 0; function count() { i += direction; direction *= (((i % 100) == 0) ? -1 : 1); } 
+6
source

The expression abs((i % 200) - 100) makes the sawtooth pattern you want as i increases.

So something like this:

 var i = 100; while (1) { var j = Math.abs((i % 200) - 100); // Use j // ... i += 1; } 
+4
source

You may have a variable that will add or decrease the amount if it is positive or negative. Therefore, you just need to change the sign of the variable.

 var countingUp = 1; var i = 0; function count() { i += (1 * countingUp); if (i == 100 || i == 0) { countingUp *= -1; } } 

the violin is here .

To avoid infinite recursion, just use setInterval ().

 window.setInterval( count, 1 ); 
+3
source

Just for fun:

 function createCounter(min,max) { var dir = -1, val = min; return function() { return val += ((val >= max || val <= min) ? dir=-dir : dir); } } 

and then use it

 var counter = createCounter(0,5); counter(); // 1 counter(); // 2 counter(); // 3 counter(); // 4 counter(); // 5 counter(); // 4 counter(); // 3 counter(); // 2 counter(); // 1 counter(); // 0 counter(); // 1 counter(); // 2 
+1
source

Source: https://habr.com/ru/post/902707/


All Articles