-
-
Notifications
You must be signed in to change notification settings - Fork 5.5k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add _.chunk to Array functions. #1919
Changes from 7 commits
e917a18
db7f405
750f22c
dbc7375
e3035ba
63652f6
a59a6f9
7d4034c
ce3a67a
0c6d140
185abf6
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -646,6 +646,21 @@ | |
|
||
return range; | ||
}; | ||
|
||
// Split an **array** into several arrays containing **count** or less elements | ||
// of initial array | ||
_.chunk = function(array, count) { | ||
var result = []; | ||
|
||
if (array == null || count <= 0) return []; | ||
if (count >= array.length) return array; | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. First, seems unnecessary, second, we should always produce a new array in case they decide to modify it. I would kill this line |
||
|
||
for (var i = 0, lng = array.length; i < lng; i += count) { | ||
result.push(array.slice(i, i + count)); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. worth saving characters? for (var i = 0, lng = array.length; i < lng;) {
result.push(array.slice(i, i += count));
} |
||
} | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I would probably write line 655-659 as var i = 0, length = array && array.length, j = 0;
while (i < length && count >= 0) {
if (i % count) result[j++] = [];
result[j].push(array[i]);
} (untested). I would be curious to see some benchmarks |
||
|
||
return result; | ||
}; | ||
|
||
// Function (ahem) Functions | ||
// ------------------ | ||
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
hmm, I wonder if it's faster to compute the length
new Array(Math.ceil(array.length / count))
- feel free not to bother with it