diff --git a/src/js/utils/Array.js b/src/js/utils/Array.js index bfa08536..4e2753d0 100644 --- a/src/js/utils/Array.js +++ b/src/js/utils/Array.js @@ -12,22 +12,29 @@ return match; }, - chunk : function (array, chunks) { - var chunked = []; + /** + * Split a provided array in a given amount of chunks. + * For instance [1,2,3,4] chunked in 2 parts will be [1,2] & [3,4]. + * @param {Array} array the array to chunk + * @param {Number} chunksCount the number of chunks to create + * @return {Array} array of arrays containing the items of the original array + */ + chunk : function (array, chunksCount) { + var chunks = []; // We cannot have more chunks than array items. - chunks = Math.min(chunks, array.length); + chunksCount = Math.min(chunksCount, array.length); - // chunks should be at least 1 - chunks = Math.max(1, chunks); + // chunksCount should be at least 1 + chunksCount = Math.max(1, chunksCount); - var step = Math.round(array.length / chunks); - for (var i = 0 ; i < chunks ; i++) { - var isLast = i == chunks - 1; + var step = Math.round(array.length / chunksCount); + for (var i = 0 ; i < chunksCount ; i++) { + var isLast = i == chunksCount - 1; var end = isLast ? array.length : (i + 1) * step; - chunked.push(array.slice(i * step, end)); + chunks.push(array.slice(i * step, end)); } - return chunked; + return chunks; } }; diff --git a/src/js/utils/serialization/Serializer.js b/src/js/utils/serialization/Serializer.js index b160c210..7cea3131 100644 --- a/src/js/utils/serialization/Serializer.js +++ b/src/js/utils/serialization/Serializer.js @@ -42,8 +42,19 @@ frameCount : frames.length }; + // A layer spritesheet data can be chunked in case the spritesheet PNG is to big to be + // converted to a dataURL. + // Frames are divided equally amongst chunks and each chunk is converted to a spritesheet + // PNG. If any chunk contains an invalid base64 PNG, we increase the number of chunks and + // retry. var chunks = []; while (!areChunksValid(chunks)) { + if (chunks.length > frames.length) { + // Something went horribly wrong. + chunks = []; + break; + } + // Chunks are invalid, increase the number of chunks by one, and chunk the frames array. var frameChunks = pskl.utils.Array.chunk(frames, chunks.length + 1); diff --git a/test/js/utils/ArrayTest.js b/test/js/utils/ArrayTest.js index bded97b6..c52d422c 100644 --- a/test/js/utils/ArrayTest.js +++ b/test/js/utils/ArrayTest.js @@ -65,4 +65,4 @@ describe("Array utils", function() { expect(chunks.length).toBe(1); expect(chunks[0]).toEqual([1, 2, 3, 4]); }); -}); \ No newline at end of file +});