Skip to content

Instantly share code, notes, and snippets.

@ChillyBwoy
Created May 31, 2011 00:39
Show Gist options
  • Save ChillyBwoy/999690 to your computer and use it in GitHub Desktop.
Save ChillyBwoy/999690 to your computer and use it in GitHub Desktop.
inGroupsOf function from prototype.js implementation for underscore.js
_.mixin({
inGroupsOf: function(array, number, fillWith) {
fillWith = fillWith || null;
var index = -number, slices = [];
if (number < 1) return array;
while ((index += number) < array.length) {
var s = array.slice(index, index + number);
while(s.length < number)
s.push(fillWith);
slices.push(s);
}
return slices;
}
});
/*
_.inGroupsOf(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i'], 3);
//-> [["a", "b", "c"], ["d", "e", "f"], ["g", "h", "i"]]
_.inGroupsOf(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i'], 4);
//-> [["a", "b", "c", "d"], ["e", "f", "g", "h"], ["i", null, null, null]]
_.inGroupsOf(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i'], 4, 'foo');
//-> [["a", "b", "c", "d"], ["e", "f", "g", "h"], ["i", "foo", "foo", "foo"]]
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment