Last active
October 8, 2015 19:18
-
-
Save timruffles/3377784 to your computer and use it in GitHub Desktop.
underscore chunk method
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
// Turns a list into a list of lists of specified lengths. | |
_.chunk = function(array,chunkSize) { | |
return _.reduce(array,function(reducer,item,index) { | |
reducer.current.push(item); | |
if(reducer.current.length === chunkSize || index + 1 === array.length) { | |
reducer.chunks.push(reducer.current); | |
reducer.current = []; | |
} | |
return reducer; | |
},{current:[],chunks: []}).chunks | |
}; | |
// test | |
"chunk reduces an array to chunks": function() { | |
var chunked = _.chunk(["a","a","b","b","c"],2); | |
assert.equals(chunked[0],["a","a"]); | |
assert.equals(chunked[2],["c"]); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Oh hai @timruffles. I just found myself doing the same thing for edutainment, and then stumbled on this here beauty!
We ended up with:
...for other internet travellers who stumble here, you'll probably want something like: https://lodash.com/docs#chunk