Search code examples
javascriptpaginationnumbers

javascript number counting


I am slightly stuck on the javascript logic to accomplish this.

Basically

If I give a number (say 30)

I want to show 5 either side.

so

25 26 27 28 29 30 31 32 33 34 35

That part is easy.

But then I need to handle cases where the number is below 5 (say 3).

What I want to to is,

for every number not shown on the right, add it to the left

so

1 2 3 4 5 6 7 8 9 10 11

But then I need to handle cases where the number is above a (maximum-5) (say maximum = 100, number = 98).

What I want to to is,

for every number not shown on the left, add it to the right

so

90 91 92 93 94 95 96 97 98 99 100

But then I need to handle cases where the maximum is below 10 (say number = 3, maximum = 8

What I want to to is,

only show the applicable range

so

1 2 3 4 5 6 7 8

But I am not sure on the logic


Solution

  • function ranger(num) {
      //Establish limits and pre/post array storage
      var low = 0, high = 100, howMany = 5;
      var pre = [];
      var post = [];
    
      //Increment/decrement if appropriate
      for(x=1;x<=howMany;x++) {
        if((num-x) > low) { pre.push(num-x); }
        if((num+x) < high) { post.push(num+x); }
      }
      pre.reverse();
    
      alert("Before: "+pre+'\nNumber: '+num+'\nAfter: '+post)
    }
    
    ranger(7);
    ranger(2);
    ranger(96);