I have three methods, for example:
function method1(){
console.log('method1');
}
function method2(){
console.log('method2');
}
function method3(){
console.log('method3');
}
Now I will apply these methods in an if else condition, as shown below:
for(var i=0;i<100;i++){
if(i<4){
method1();
}
else if(i==4){
method2();
}
else if(i>4 && i<8){
method3();
}
else if(i==8){
method2();
}
else if(i>8 && i<12){
method1();
}
...........
}
Like me, I have to iterate to 100 or say if it is even longer, then the encoding process will be so long and can be annoying.
So, I thought there might be an easier way to solve this problem.
To make this concept even clearer what I wanted to do, I present to you a graph with which you could easily solve the following solution:

you can skip the following:
In preparing the schedule for this issue, the following concept occurred to me:
From the above chart
- You may know that the first 4 iterations have method1.
- 5- (4), 9- (8), 13- (12), 17- (16), 21- (20), 25- (24)
29 (28) .. 2.
- method2 2
3.
- 1.
for(var i=0; i<100; i++){
//find the series 5th, 9th, 13th, and so on and apply method2:
if( i == 5 + 4 * n){
method2();
}
//find the series between 9th and 5th and so on and apply method3:
else if( i > ( 5 + 4 * n ) && i < ( 5 + 4 * n - 1) ){
method3();
}
//for other iterations apply method 1:
else{
method1();
}
}//end for loop
, , n. , n , for(var i=0,n=0;i<100;i++), , 5, n 5, 5 + 4 * 5 = 25 .
for(var i=0,n=0; i<100; i++){
if(i%4==0){
n=-1;
}
//now i becomes equal when i is 5 then n is -1 at 4th i so 0 at 5th i and 5+4*0 = 5.... matched
//now check for next 9th i equals n: i is 9 then n is -1 at 8th i so 0 at 9th i and 5+4*0=5... not matched as this time it should be 1 for n
Ummm, , n -1 4- 0 8- 1 12- .......
, .
, , .
.