Skip to content

Commit 4d95823

Browse files
Petr Archakovmegawac
authored andcommitted
Add _.chunk to Array functions.
fix _.chunk function fix _.chunk function Do not return original array if chunkin in more then array size parts Do not return original array if chunkin in more then array size parts spaces clean up
1 parent 4747d4e commit 4d95823

File tree

2 files changed

+29
-1
lines changed

2 files changed

+29
-1
lines changed

test/arrays.js

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -538,5 +538,19 @@
538538
deepEqual(_.range(12, 7, -2), [12, 10, 8], 'range with three arguments a & b & c, a > b, c < 0 generates an array of elements a,a-c,a-2c and ends with the number not less than b');
539539
deepEqual(_.range(0, -10, -1), [0, -1, -2, -3, -4, -5, -6, -7, -8, -9], 'final example in the Python docs');
540540
});
541-
541+
542+
test('chunk', function() {
543+
deepEqual(_.chunk([], 2), [], 'chunk for empty array returns an empty array');
544+
deepEqual(_.chunk(null, 2), [], 'chunk for null returns an empty array');
545+
546+
deepEqual(_.chunk([1, 2, 3], 0), [], 'chunk into parts of 0 elements returns an empty array');
547+
deepEqual(_.chunk([1, 2, 3], -1), [], 'chunk into parts of negative amount of elements returns an empty array');
548+
549+
deepEqual(_.chunk([1, 2, 3], 3), [[1, 2, 3]], 'chunk into parts of current array length elements returns the original array');
550+
deepEqual(_.chunk([1, 2, 3], 5), [[1, 2, 3]], 'chunk into parts of more then current array length elements returns the original array');
551+
552+
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');
553+
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');
554+
});
555+
542556
}());

underscore.js

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -696,6 +696,20 @@
696696
return range;
697697
};
698698

699+
// Split an **array** into several arrays containing **count** or less elements
700+
// of initial array
701+
_.chunk = function(array, count) {
702+
var result = [];
703+
704+
if (array == null || count <= 0) return [];
705+
706+
for (var i = 0, length = array.length; i < length;) {
707+
result.push(array.slice(i, i += count));
708+
}
709+
710+
return result;
711+
};
712+
699713
// Function (ahem) Functions
700714
// ------------------
701715

0 commit comments

Comments
 (0)