loop counting to 100 and back to 0 and up to 100 again and so on

I must admit, I am not a mathematical expert, thats why I cant solve the following problem to my satisfaction.

I have a number, say i=0. I have a function that increases i on each call by 1 and then calls itself again, increasing i another time and another and another ... When reached 100 I want it to count backwards to 0 and then up again, kind of like an endles loop with i going up and down like an elevator. Whats an elegant solution for that?

My solution so far:

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.

Answers


Looks ok to me, but will probably 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);
}

Need Your Help

libgdx changing sprite color while hurt

java colors libgdx sprite game-engine

I am using libgdx to make a little platformer and I would like to make the enemies blink in red while the player hurt them with his weapon.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.