Created
September 2, 2018 08:15
-
-
Save nluo/7c13fff648c9f96447281e48ab9d094a to your computer and use it in GitHub Desktop.
Array Chuck question
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
// --- Directions | |
// Given an array and chunk size, divide the array into many subarrays | |
// where each subarray is of length size | |
// --- Examples | |
// chunk([1, 2, 3, 4], 2) --> [[ 1, 2], [3, 4]] | |
// chunk([1, 2, 3, 4, 5], 2) --> [[ 1, 2], [3, 4], [5]] | |
// chunk([1, 2, 3, 4, 5, 6, 7, 8], 3) --> [[ 1, 2, 3], [4, 5, 6], [7, 8]] | |
// chunk([1, 2, 3, 4, 5], 4) --> [[ 1, 2, 3, 4], [5]] | |
// chunk([1, 2, 3, 4, 5], 10) --> [[ 1, 2, 3, 4, 5]] | |
function chunk(array, size) { | |
if (array.length === 0) { | |
return [] | |
} | |
const left = array.slice(0, size) | |
const right = array.slice(size) | |
return [left].concat(left, chunk(right, size)) | |
} | |
module.exports = chunk; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment