Skip to content

Instantly share code, notes, and snippets.

@robotdana
Created August 18, 2010 08:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save robotdana/533983 to your computer and use it in GitHub Desktop.
Save robotdana/533983 to your computer and use it in GitHub Desktop.
(function($){
$.fn.extend({
unslice: function(min, max){
/* returns a jQuery object containing whatever elements
would've been ditched if we'd done a slice() with the same parameters */
if ($(this).length && min !== undefined){
var before = min > 0 ? $(this).slice(0, min) : {};
var after = max !== undefined ? $(this).slice(max) : {};
return $(this).pushStack(after.add(before), "unslice");
}
},
continualSlice: function(min, max, un){
// like slice, but wraps round the array rather than truncating at the end.
// fails if min and max are further apart than the length.
//if un is true it returns whatever isn't between min and max
var length = $(this).length;
if (length && min !== undefined && max !== undefined && max - min <= length){
//if it's entirely out-of-bounds, bring it in so it crosses the end
while (min < 0) {max += length; min += length}
while (min >= length) {max -= length; min -= length}
//it now or always was entirely in bounds, just a normal slice
if (max <= length) {
if (un){ return $(this).pushStack($(this).unslice(min, max));
} else { return $(this).pushStack($(this).slice(min, max));}
}
if (un){ return $(this).pushStack($(this).slice(max, min));
} else { var end = $(this).slice(min);
var start = $(this).slice(0, max-length);
return $(this).pushStack(end.concat(start), "continualSlice");
}
}
},
continualUnslice: function(min, max) {
// I intended this to be a separate method, but they're just so damn similar.
return $(this).continualSlice(min, max, true);
}
});
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment