diff --git a/src/js/utils/Array.js b/src/js/utils/Array.js index 3bc13563..bfa08536 100644 --- a/src/js/utils/Array.js +++ b/src/js/utils/Array.js @@ -10,6 +10,24 @@ match = filtered[0]; } return match; + }, + + chunk : function (array, chunks) { + var chunked = []; + + // We cannot have more chunks than array items. + chunks = Math.min(chunks, array.length); + + // chunks should be at least 1 + chunks = Math.max(1, chunks); + + var step = Math.round(array.length / chunks); + for (var i = 0 ; i < chunks ; i++) { + var isLast = i == chunks - 1; + var end = isLast ? array.length : (i + 1) * step; + chunked.push(array.slice(i * step, end)); + } + return chunked; } }; diff --git a/test/js/utils/ArrayTest.js b/test/js/utils/ArrayTest.js new file mode 100644 index 00000000..bded97b6 --- /dev/null +++ b/test/js/utils/ArrayTest.js @@ -0,0 +1,68 @@ +describe("Array utils", function() { + + beforeEach(function() {}); + afterEach(function() {}); + + it("chunks correctly", function() { + // when + var array = [1, 2, 3, 4]; + + // then + var chunks = pskl.utils.Array.chunk(array, 1); + + // verify + expect(chunks.length).toBe(1); + expect(chunks[0]).toEqual([1, 2, 3, 4]); + + // then + chunks = pskl.utils.Array.chunk(array, 2); + + // verify + expect(chunks.length).toBe(2); + expect(chunks[0]).toEqual([1, 2]); + expect(chunks[1]).toEqual([3, 4]); + + // then + chunks = pskl.utils.Array.chunk(array, 3); + + // verify + expect(chunks.length).toBe(3); + expect(chunks[0]).toEqual([1]); + expect(chunks[1]).toEqual([2]); + expect(chunks[2]).toEqual([3, 4]); + + // then + chunks = pskl.utils.Array.chunk(array, 4); + + // verify + expect(chunks.length).toBe(4); + expect(chunks[0]).toEqual([1]); + expect(chunks[1]).toEqual([2]); + expect(chunks[2]).toEqual([3]); + expect(chunks[3]).toEqual([4]); + + // then + chunks = pskl.utils.Array.chunk(array, 5); + + // verify + expect(chunks.length).toBe(4); + expect(chunks[0]).toEqual([1]); + expect(chunks[1]).toEqual([2]); + expect(chunks[2]).toEqual([3]); + expect(chunks[3]).toEqual([4]); + + // then + chunks = pskl.utils.Array.chunk(array, 0); + + // verify + expect(chunks.length).toBe(1); + expect(chunks[0]).toEqual([1, 2, 3, 4]); + + // then + chunks = pskl.utils.Array.chunk(array, -1); + + // verify + expect(chunks.length).toBe(1); + expect(chunks[0]).toEqual([1, 2, 3, 4]); + }); +}); \ No newline at end of file