Created
October 27, 2017 11:54
-
-
Save freebeans/27d7452c64e779ea3061ddd708ed29f5 to your computer and use it in GitHub Desktop.
Javascript chunknize
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
// chunknize(data, chunksize, callback) | |
// Separa o vetor "data" em vetores de tamanho "chunksize". | |
// Chama "callback" com o vetor de vetores como argumento. | |
// data: array que será separada em blocos de certo tamanho | |
// chunksize: tamanho de cada novo bloco | |
// callback(chunks): função que receberá a lista de blocos | |
// Se "chunksize" for zero, um único bloco será criado com todos os itens. ( [[1, 2, 3]] ) | |
// Se "chunksize" > "data.length", novamente um único bloco será criado. ( [[1, 2, 3]] ) | |
// Exemplo: separando um vetor de 5 elementos em vetores com 2 elementos ou menos | |
// | |
// chunknize( | |
// [1, 2, 3, 4, 5], | |
// 2, | |
// (chunks)=>{ | |
// console.log(chunks); | |
// } | |
// ); | |
// | |
// Resultado: [ [1, 2], [3, 4], [5] ] | |
function chunknize(data, chunksize, callback) { | |
var chunks = []; | |
data.forEach((item)=>{ | |
if(!chunks.length || chunks[chunks.length-1].length == chunksize) | |
chunks.push([]); | |
chunks[chunks.length-1].push(item); | |
}); | |
callback(chunks); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment