Setting the order with set()

Let's look at what happens when you iterate over a map:

const myMap = Map()
.set('one', 1)
.set('two', 2)
.set('three', 3);

myMap
.forEach(i => console.log('myMap', i));
// -> myMap 1
// -> myMap 2
// -> myMap 3

The iteration order is the same as the order in which you set the values. However, this iteration order isn't guaranteed. You could see a different order the next time you iterate over myMap. Let's try this with an ordered map now:

const myOrderedMap = OrderedMap()
.set('three', 3)
.set('two', 2)
.set('one', 1);

myOrderedMap
.forEach(i => console.log('myOrderedMap', i));
// -> myOrderedMap 3
// -> myOrderedMap 2
// -> myOrderedMap 1

Our map, myOrderedMap, will always have the same iteration order. The order is defined as the order in which items are set. Since we're setting the value 3 first, it has an index of 0 (internally) and a key of three. If you were iterating over this map to render data in a user interface, consistent iteration order is important—the OrderedMap collections provide this guarantee.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.141.152.173