Skip to content

Instantly share code, notes, and snippets.

@FGRibreau
Forked from loginx/gist:810311
Created January 25, 2012 21:12
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save FGRibreau/1678749 to your computer and use it in GitHub Desktop.
Save FGRibreau/1678749 to your computer and use it in GitHub Desktop.
Underscore.js mixin to emulate ruby's Array#each_slice method.
/**
* Underscore.js mixin to emulate Ruby's Enumerable#each_slice method.
* http://www.ruby-doc.org/core/classes/Enumerable.html#M001514
*
*/
_.mixin({
// _.each_slice(obj, slice_size, [iterator], [context])
each_slice: function(obj, slice_size, iterator, context) {
var collection = obj.map(function(item) { return item; }), o = [], t = null, it = iterator || function(){};
if (typeof collection.slice !== 'undefined') {
for (var i = 0, s = Math.ceil(collection.length/slice_size); i < s; i++) {
it.call(context, (t = _(collection).slice(i*slice_size, (i*slice_size)+slice_size), o.push(t), t), obj);
}
}
return o;
}
});
/* Example:
>>> _.each_slice([1,2,3,4,5,6,7,8,9,10], 4)
[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10]]
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment