title: If index is out of bounds of array, set index to closest boundary
body: <p>Let's say we have an array that can have a length of 1 to ??</p>
  
  <p>We have a way of navigating this array up or down by clicking a button that either navigates upward or downward, which is displayed in the DOM (think pagination).</p>
  
  <p>We would want our navigation to stop when either we are out of the lower bound, or stop when our navigation is out of the upper bound.</p>
  
  <p>When we reach the lower-bound we would know this by the value <strong>-1</strong></p>
  
  <p>When we reach the upper-bound we would know this by the value <strong>( > array.length - 1 )</strong>.</p>
  
  <p>Our function accepts the parameter index as shown</p>
  
  <pre><code>function goToChapter( index ){
    // compute value of index to within bounds.
    return array[ index ];
  }
  </code></pre>
  
  <p>Let's say all we want to do is use the computed within bounds index to get a value from the returned array. </p>
  
  <blockquote>
    <p>Examples</p>
  </blockquote>
  
  <pre><code>var array ["chapZero", "chapOne", "chapTwo", "chapThree"];
  
  goToChapter( 2 );
  =&gt; "chapTwo;
  
  goToChapter( 4 );
  =&gt; "chapThree"; // because four is out of upper bound so index became three.
  
  goToChapter( -1 );
  =&gt; "chapZero"; // because -1 is our of lower bound so index became zero.
  </code></pre>
  
  <p>I realize this can be done with a few if statements, I am looking for a way to use some sort of math formula that perhaps</p>
  
  <ol>
  <li>converts any negative number to 0;</li>
  <li>leaves any positive number alone;</li>
  <li>uses the length of the array to determine when to return the upper limit.</li>
  </ol>
  
  <p><strong>UPDATE</strong></p>
  
  <p>I'm going with Andand's answer. I've added enough to copy paste the solution into the console if you find this helpful and want to test it out.</p>
  
  <pre><code>var array = [0,1,2,3,4];
  
  function goToChapter( index, array ){
    return array[(Math.min( array.length - 1, Math.max( 0, index )))];
  }
  
  goToChapter( -1, array ); =&gt; 0;
  
  goToChapter( 3, array ); =&gt; 3;
  
  goToChapter( 8, array ); =&gt; 4;
  </code></pre>
  
  <p>Thanks Andand.</p>
  
  <p><strong>NOTE:</strong></p>
  
  <p>I also found this helpful, but not as fast.</p>
  
  <pre><code>function setWithinArrayBounds( index, array ){
    return !!index ? 0 : index &gt; ( array.length - 1 ) ? ( array.length - 1 ) : index;
  }
  </code></pre>