Created
May 31, 2011 00:39
-
-
Save ChillyBwoy/999690 to your computer and use it in GitHub Desktop.
inGroupsOf function from prototype.js implementation for underscore.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
_.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