Improved .get() for negative Indices

Benchmark created by Anton M. on


Description

Improved version of .get() for negative indices.

Also makes .get( negativeNumberLargerThenElementCount ) behave the same as .get( numberLargerThenElementCount ) both return now undefined. Before .get( negativeNumberLargerThenElementCount ) always returned the first element too to the use of slice.

Preparation HTML

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.js"></script>
<div id="foo" style="display:none"><p>foo</p><p>foo</p><p>foo</p><p>foo</p><p>foo</p><p>foo</p><p>foo</p><p>foo</p><p>foo</p><p>foo</p><p>foo</p><p>foo</p><p>foo</p><p>foo</p><p>foo</p><p>foo</p><p>foo</p><p>foo</p><p>foo</p><p>foo</p><p>foo</p><p>foo</p><p>foo</p><p>foo</p><p>foo</p><p>foo</p><p>foo</p><p>foo</p><p>foo</p><p>foo</p><p>foo</p><p>foo</p><p>foo</p><p>foo</p><p>foo</p><p>foo</p><p>foo</p><p>foo</p><p>foo</p><p>foo</p><p>foo</p><p>foo</p><p>foo</p><p>foo</p><p>foo</p><p>foo</p><p>foo</p><p>foo</p><p>foo</p><p>foo</p></div>
<script>
  var $sel = $("#foo p");
  
  (function($) {
   $.fn.myGet = function(num) {
    return num == null ?
    // Return a 'clean' array
    this.toArray() :
    // Return just the object
    (num < 0 ? this[this.length + num] : this[num]);
   }
  })(jQuery);
</script>

Test runner

Ready to run.

Testing in
TestOps/sec
orig
$sel.get(-1);
ready
new
$sel.myGet(-1);
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.

  • Revision 1: published by Anton M. on