Better readability for multiple .add with .eq in it

I’m collecting multiple li into one object for a pagination.

var li = $(this).find('li');
if(li.length > 15) {
    var activeId = li.filter('.active').index();
    li.eq(0)
        .add(li.eq(1))
        .add(li.eq(2))
        .add(li.eq(-1))
        .add(li.eq(-2))
        .add(li.eq(-3))
        .add(li.eq(activeId))
        .add(li.eq(activeId-1))
        .add(li.eq(activeId-2))
        .add(li.eq(activeId-3))
        .add(li.eq(activeId+1))
        .add(li.eq(activeId+2))
        .add(li.eq(activeId+3))
        .addClass('dosomething');
    li.each(function() {
        // do something...
    });
}

HTML example:

<ul>
    <li><a href="#…">1</a></li>
    <li class="active"><a href="#…">2</a></li>
    <li><a href="#…">3</a></li>
    <li><a href="#…">4</a></li>
    <li><a href="#…">5</a></li>
    ...
    <li><a href="#…">16</a></li>
</ul>

But this looks quite straight forward and not very performant and readable. So i’m searching for a method to write this code more readable.

Answer

To reduce your jQuery Array collection to a specific start-end index set of Elements – you can use Array.prototype.slice(beginIndex, endIndex(not inclusive))

$("ul").each(function() {

  var $li = $(this).find('li'),
      tot = $li.length;

  if (tot > 15) {

    var idx  = $li.filter('.active').index(),
        first3   = $li.slice(0, 3),                                         // Slice
        middle7  = $li.slice(Math.max(0, idx - 3), Math.min(tot, idx + 4)), // Slice
        last3    = $li.slice(tot - 3, tot),                                 // Slice
        $group   = first3.add( middle7 ).add( last3 );                 // Group them

    $group.addClass("dosomething").each(function() {
       // do something on that group of LI elements
    });

  }

});
li.active {
  color: red;
}

.dosomething {
  color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<ul>
  <li>1</li>
  <li>2</li>
  <li>3</li>
  <li>4</li>
  <li>5</li>
  <li>6</li>
  <li>7</li>
  <li class="active">8</li>
  <li>9</li>
  <li>10</li>
  <li>11</li>
  <li>12</li>
  <li>13</li>
  <li>14</li>
  <li>15</li>
  <li>16</li>
  <li>17</li>
  <li>18</li>
</ul>

P.S: if at any time you need to target the LI that are not in our $group you can simply do:

var $allOther = $li.not( $group );