Created
February 3, 2017 13:26
-
-
Save yowcow/aad5dd8e5918fdf8af1a7e140c16c68c to your computer and use it in GitHub Desktop.
Reduce an array into array of arrays
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
const expect = require('expect') | |
const groupItems = (array = [], count) => | |
array.reduce( | |
(prev, cur) => { | |
const lastIndex = prev.length - 1 | |
return lastIndex === -1 ? [[cur]] | |
: prev[lastIndex].length === count ? [...prev, [cur]] | |
: [...prev.slice(0, -1), [...prev[lastIndex], cur]] | |
}, | |
[] | |
) | |
describe('groupItems', () => { | |
it('should create a group of 3 elements', () => { | |
const groups = groupItems([1, 2, 3], 3) | |
expect(groups).toEqual( | |
[ | |
[1, 2, 3] | |
] | |
) | |
}) | |
it('should create 2 groups of 3 elements', () => { | |
const groups = groupItems([1, 2, 3, 4, 5, 6], 3) | |
expect(groups).toEqual( | |
[ | |
[1, 2, 3], | |
[4, 5, 6] | |
] | |
) | |
}) | |
it('should create a group of 2 elements, last group with 1 element', () => { | |
const groups = groupItems([1, 2, 3], 2) | |
expect(groups).toEqual( | |
[ | |
[1, 2], | |
[3] | |
] | |
) | |
}) | |
it('should create no group from undefined', () => { | |
expect(groupItems()).toEqual([]) | |
}) | |
}) |
Author
yowcow
commented
Feb 3, 2017
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment