Skip to content

Instantly share code, notes, and snippets.

@abernier
Created January 21, 2012 17:46
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 abernier/1653407 to your computer and use it in GitHub Desktop.
Save abernier/1653407 to your computer and use it in GitHub Desktop.
$.fn.segment
(($) ->
###
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)
###
$.fn.segment = (start, width = 1) ->
length = @length
end = undefined
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;
end = undefined if (end == 0)
@slice(start, end)
)(jQuery)
@abernier
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment