Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to chunk ImmutableJS list into multiple lists

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.

like image 993
Gerard Clos Avatar asked Jun 28 '16 16:06

Gerard Clos


2 Answers

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.

like image 87
jokka Avatar answered Nov 12 '22 09:11

jokka


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.

like image 21
Brian Neisler Avatar answered Nov 12 '22 08:11

Brian Neisler