views:

167

answers:

4

I've got a fairly simple pagination algorithm here but it's not working the way I'd like it to.

Currently it's displaying like this

1 2 3 ... 33 34 35 [36] 37 38 ... 47 48 49 50

When it should be displaying like this

1 2 3 ... 33 34 35 [36] 37 38 39 ... 48 49 50

Here's my code, I wrote it very quickly. It also seems to continuously run (The loop doesn't stop) but I've no idea why.

$(function(){
            var pages = 50;                 //Total number of pages
            var current = 36;               //The current page we are on
            var before = 3;                 //Number of links to display before current
            var after = 3;                  //Same as above but after
            var start = (current - before); //The number of the first link
            var end = (current + after);    //Number of the end link

            for(var i = 1; i <= pages; i++){
                if(i == (before + 1)){
                    i = start;
                    document.write('...');
                }
                else if(i == (current + after)){
                    i = (pages - after);
                    document.write('...');
                }
                if(i == current){
                    document.write(' ['+i+'] ');
                }
                else{
                    document.write(' '+i+' ');
                }
            }
        });
+2  A: 

Please fix after to after + 1 in 2 places in all places in your loop where you use it.

Also, I am not sure your code will work correctly for edge cases (e.g. where current == 2) - you may want to test that

DVK
Actually, he can't just change the variable, since `(pages - (after + 1)) == 46`. The second option is better, since it would produce `(pages - after + 1) == 48`, the correct code in the second instance.
Tim Yates
+1  A: 
  1. current + after is 39 (36 + 3) here, so no wonder it displays "..." instead of 39, increase "after" by 1 to fix this
  2. after looking at the code for several minutes, I don't have a clue why it should run forever :) Have you tried writing "i" to the console to check what values it takes and why it never reaches its "final value"?
Select0r
A: 

There is a reason why arrays used zero-based indexing in most languages: the math is just simpler. In your case, since you obviously can't use zero-based indexing, you'll just have to fix the off-by-one errors:

else if(i == (current + after + 1)){
    i = (pages - after + 1);
    document.write('...');
}
Tim Yates
+2  A: 

If (current + after) > (pages - after) and (current + after) < pages then this code will run forever because of:

else if(i == (current + after)){
    i = (pages - after);
    document.write('...');
}

Each time i reaches current + after, it will be reduced to pages - after and that cycle will continue indefinitely

Dancrumb