Skip to content

Commit

Permalink
Merge pull request #2252 from megawac/chunk
Browse files Browse the repository at this point in the history
Chunk
  • Loading branch information
jridgewell committed Jul 28, 2015
2 parents 4747d4e + 97dee13 commit d845c0b
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 0 deletions.
15 changes: 15 additions & 0 deletions test/arrays.js
Original file line number Diff line number Diff line change
Expand Up @@ -539,4 +539,19 @@
deepEqual(_.range(0, -10, -1), [0, -1, -2, -3, -4, -5, -6, -7, -8, -9], 'final example in the Python docs');
});

test('chunk', function() {
deepEqual(_.chunk([], 2), [], 'chunk for empty array returns an empty array');

deepEqual(_.chunk([1, 2, 3], 0), [], 'chunk into parts of 0 elements returns empty array');
deepEqual(_.chunk([1, 2, 3], -1), [], 'chunk into parts of negative amount of elements returns an empty array');
deepEqual(_.chunk([1, 2, 3]), [], 'defaults to empty array (chunk size 0)');

deepEqual(_.chunk([1, 2, 3], 1), [[1], [2], [3]], 'chunk into parts of 1 elements returns original array');

deepEqual(_.chunk([1, 2, 3], 3), [[1, 2, 3]], 'chunk into parts of current array length elements returns the original array');
deepEqual(_.chunk([1, 2, 3], 5), [[1, 2, 3]], 'chunk into parts of more then current array length elements returns the original array');

deepEqual(_.chunk([10, 20, 30, 40, 50, 60, 70], 2), [[10, 20], [30, 40], [50, 60], [70]], 'chunk into parts of less then current array length elements');
deepEqual(_.chunk([10, 20, 30, 40, 50, 60, 70], 3), [[10, 20, 30], [40, 50, 60], [70]], 'chunk into parts of less then current array length elements');
});
}());
13 changes: 13 additions & 0 deletions underscore.js
Original file line number Diff line number Diff line change
Expand Up @@ -696,6 +696,19 @@
return range;
};

// Split an **array** into several arrays containing **count** or less elements
// of initial array
_.chunk = function(array, count) {
if (count == null || count < 1) return [];

var result = [];
var i = 0, length = array.length;
while (i < length) {
result.push(slice.call(array, i, i += count));
}
return result;
};

// Function (ahem) Functions
// ------------------

Expand Down

0 comments on commit d845c0b

Please sign in to comment.