JSFiddle - React, Tailwind, and code Playground

by abernier

HTML

<ul>
    <li>A</li>
    <li>B</li>
    <li>C</li>
    <li>D</li>
    <li>E</li>
</ul>

JavaScript

(function($) {
  /*
    Grab a segment of a jQuery collection
      * start: a zero-based index from which to grab
      * width: the width of the segment (default: 1)
  
    Examples:
  
    | A | B | C | D | E |    $myList
     <->                       .segment( 0)
         <----->               .segment( 1, 2)
                     <->       .segment(-1)
         <------------->       .segment(-1, 4)
  */  return $.fn.segment = function(start, width) {
    var end, length;
    if (width == null) width = 1;
    length = this.length;
    end = void 0;
    width = Math.max(1, width);
    width = Math.min(length, width);
    if (start >= 0) {
      start = Math.min(length - width, start);
      end = start + width;
    } else {
      start = Math.max(-length, start);
      start = Math.min(-width, start);
      end = start + width;
      if (end === 0) end = void 0;
    }
    return this.slice(start, end);
  };
})(jQuery);


console.log($('li').segment(0));
console.log($('li').segment(1, 2));
console.log($('li').segment(2, 5));

console.log($('li').segment(-1));
console.log($('li').segment(-1, 2));