Is there a way to separate an ImmutableJS list into a list of multiple lists ? I'm basically looking for something like lodash's chunk but for ImmutableJS lists.
I could transform my list into an Array before passing it to chunk and convert back the response to an ImmutableJS list, but I'm told shallow transformations are not efficient and my lists are quite big.
Thank you, G.
Immutable.js does not provide it right out of the box.
Here’s the function which splits the list into equally sized chunks. The last chunk may be smaller if the list can not be split evenly.
function splitIntoChunks(list, chunkSize = 1) {
return Immutable.Range(0, list.count(), chunkSize)
.map(chunkStart => list.slice(chunkStart, chunkStart + chunkSize));
}
It first enumerates the indexes where each chunk should start and then transforms the list of indexes into a list of slices spanning from each index to the index plus chunk size.
Looks simple and efficient to me.
mudash (a lodash wrapper that provides immutable js support) provides a chunk method. It should give you what you need. No transformations performed so performance remains high.
import _ from 'mudash'
import Immutable from 'immutable'
const list = Immutable.List([1, 2, 3, 4])
_.chunk(list, 2) // List [ List [ 1, 2 ], List [ 3, 4 ] ]
Full disclosure, I am the author of the mudash module.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With