Skip to content

Instantly share code, notes, and snippets.

@yowcow
Created February 3, 2017 13:26
Show Gist options
  • Save yowcow/aad5dd8e5918fdf8af1a7e140c16c68c to your computer and use it in GitHub Desktop.
Save yowcow/aad5dd8e5918fdf8af1a7e140c16c68c to your computer and use it in GitHub Desktop.
Reduce an array into array of arrays
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([])
})
})
@yowcow
Copy link
Author

yowcow commented Feb 3, 2017

  groupItems
    ✓ should create a group of 3 elements
    ✓ should create 2 groups of 3 elements
    ✓ should create a group of 2 elements, last group with 1 element
    ✓ should create no group from undefined


  4 passing (7ms)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment