Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Immutable.js - is it possible to insert element into list at arbitrary position?

Tags:

How do I insert an element at arbitrary position of Immutable.js List?

like image 851
AndreyM Avatar asked Jan 27 '15 04:01

AndreyM


People also ask

Are lists immutable in JavaScript?

Immutable. js provides many Persistent Immutable data structures including: List , Stack , Map , OrderedMap , Set , OrderedSet and Record .

What is the use of immutable js?

Immutable. js is a library that supports an immutable data structure. It means that once created data cannot be changed. It makes maintaining immutable data structures easier and more efficient.

Should I use immutable js?

Using ImmutableJS can improve dramatically the performance of your application. And, because the immutable data never changes, you can always expect new data to be passed from the above. To make sure you are correctly comparing the data and not updating the UI when there is no change, you should always use the .

Is set immutable in JavaScript?

Iteration order of a Set is undefined, however is stable. Multiple iterations of the same Set will iterate in the same order. Set values, like Map keys, may be of any type. Equality is determined using Immutable.is , enabling Sets to uniquely include other Immutable collections, custom value types, and NaN.


2 Answers

You are looking for the splicemethod:

Splice returns a new indexed Iterable by replacing a region of this Iterable with new values.

splice(index: number, removeNum: number, ...values: any[])

Where you can specify the index and if you write 0 as removeNum it will just insert the values at the given position:

var list = Immutable.List([1,2,3,4]); console.log(list.toJS()); //[1, 2, 3, 4] var inserted = list.splice(2,0,100); console.log(list.toJS()); //[1, 2, 3, 4] console.log(inserted.toJS()); //[1, 2, 100, 3, 4]  

Demo JSFiddle.

like image 129
nemesv Avatar answered Sep 28 '22 05:09

nemesv


It is worth pointing out that you can also use the insert method which is in fact synonymous with list.splice(index, 0, value) but it feels more intuitive and improves readability greatly.

const myImmutableList = Immutable.fromJS(['foo', 'baz']) const newList = myImmutableList.insert(1, 'bar')  console.log(newList.toJS()) //["foo", "bar", "baz"] 
like image 23
Smilev Avatar answered Sep 28 '22 05:09

Smilev