Last active
May 12, 2019 17:25
-
-
Save dragonza/c9642c85854305586ab5578e0f4d9493 to your computer and use it in GitHub Desktop.
Chunk array
This file contains hidden or 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
function chunk(array, size) { | |
if (!array) return []; | |
const firstChunk = array.slice(0, size); // create the first chunk of the given array | |
if (!firstChunk.length) { | |
return array; // this is the base case to terminal the recursive | |
} | |
return [firstChunk].concat(chunk(array.slice(size, array.length), size)); | |
} | |
/* | |
Let's take an example to make it more easy to understand | |
chunk([1, 2, 3, 4], 2); | |
1st call - chunk([1,2 3,4], 2) = [[1,2]].concat(chunk([3,4], 2)); | |
2nd call - chunk([3, 4], 2) = [[3 ,4]].concat(chunk([], 2)); | |
3rd call - chunk([], 2) = [] //base case | |
so basically, chunk([1, 2, 3, 4], 2) = [[1,2]].concat([[3 ,4]].concat([])) = [[1,2], [3, 4]] | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment