How to put ImmutableJS list in multiple lists

Is there a way to separate an ImmutableJS list into a list of multiple lists? I'm basically looking for something like a lodash chunk , but for ImmutableJS lists.

I could convert my list to an array before passing it to chunk and convert the response to an ImmutableJS list, m said that small conversions are inefficient, and my lists are pretty big.

Thanks G.

+5
source share
4 answers

Immutable.js does not provide it right out of the box.

Here is a function that splits the list into equal sized pieces. The last fragment may be smaller if the list cannot be divided evenly.

function splitIntoChunks(list, chunkSize = 1) { return Immutable.Range(0, list.count(), chunkSize) .map(chunkStart => list.slice(chunkStart, chunkStart + chunkSize)); } 

First, it lists the indices at which each piece should begin, and then converts the list of indices into a list of fragments spanning from each index to the index plus the block size.

It looks simple and effective for me.

+6
source

mudash (the lodash shell that provides consistent js support) provides the chunk method . He should give you what you need. No conversions are 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.

+1
source

This chunk function from this stream seems to work well with my immutable data out of the box.

 function chunk(chunkSize, array) { return array.reduce(function(previous, current) { var chunk; if (previous.length === 0 || previous[previous.length -1].length === chunkSize) { chunk = []; // 1 previous.push(chunk); // 2 } else { chunk = previous[previous.length -1]; // 3 } chunk.push(current); // 4 return previous; // 5 }, []); // 6 } var list = Immutable.fromJS(['something','nothing','anything','hello']) console.log(chunk(3,list)) 

Example: https://jsfiddle.net/lau_chung/c67g7469/2/

0
source

I also ran into this problem and solved it with this function:

 const getListAsChunks = (list, chunkSize) => { const iterations = Math.ceil(list.count() / chunkSize); return range(0, iterations).reduce((all, item, i) => { const start = i * chunkSize; const end = (i + 1) * chunkSize; return all.push(list.slice(start, end)); }, List()); }; 

Then name it like this:

 const myChunkedList = getListAsChunks(myImmutableList, 5); 

I have imported range from lodash/range and List from immutable Hope this helps.

0
source

All Articles