add pskl.utils.Array.chunk

This commit is contained in:
juliandescottes 2016-12-18 09:16:52 +01:00
parent 156161f7c8
commit dba62d2b0d
2 changed files with 86 additions and 0 deletions

View file

@ -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;
}
};

View file

@ -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]);
});
});