From dba62d2b0d80748366ba4fcb6f953926dd4937ba Mon Sep 17 00:00:00 2001 From: juliandescottes Date: Sun, 18 Dec 2016 09:16:52 +0100 Subject: [PATCH] add pskl.utils.Array.chunk --- src/js/utils/Array.js | 18 ++++++++++ test/js/utils/ArrayTest.js | 68 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 86 insertions(+) create mode 100644 test/js/utils/ArrayTest.js diff --git a/src/js/utils/Array.js b/src/js/utils/Array.js index 3bc1356..bfa0853 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 0000000..bded97b --- /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