Skip to content

Instantly share code, notes, and snippets.

@diogobaeder
Created August 12, 2010 05:01
Show Gist options
  • Save diogobaeder/520346 to your computer and use it in GitHub Desktop.
Save diogobaeder/520346 to your computer and use it in GitHub Desktop.
// Just a simple array division to share with a friend
function divideArray(array, parts) {
if (parts == 0) return [];
var length = array.length,
blockSize = ((length + (length % parts)) / parts),
blocks = [], i;
for (i = 0; i < length; i += blockSize) {
blocks.push(array.slice(i, i + blockSize));
}
return blocks;
}
// Now, the QUnit tests I wrote to guide me through implementation
module('dividing');
test('dividing into x columns', function(){
var referenceArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];
same(divideArray(referenceArray, 2), [[1, 2, 3, 4, 5, 6], [7, 8, 9, 10, 11]], 'two columns');
same(divideArray(referenceArray, 3), [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11]], 'three columns');
same(divideArray(referenceArray, 1), [[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]], 'one column');
});
test('dividing with strange elemets', function(){
var referenceArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];
same(divideArray(referenceArray, 0), [], 'zero');
same(divideArray([], 5), [], 'empty array');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment