Most efficient way of building an indexed collection
See original GitHub issueHello and thank your for the work here. It works like a charm with React and Flux 😃
While the documentation is complete, it kinda lacks real life examples, and since I’m new to the immutable world, I have a hard time figuring out which structure I should pick in which case.
I’m not sure it’s a good thing I open a new issue each time I struggle with something (that is going to happen) so maybe I could ask them all here and then bundle your answers in a PR so it can help other newbies.
I think my main use case (and many real life use cases) is: I get JSON from the server, it looks like:
[
{
"id": "aze12",
"someField": "someValue",
....
},
{
"id": "67azea",
"someField": "someValue",
....
}
]
I think the natural way of storing with Immutable is using OrderedMap. But what is the best way of building the map with “id” or “someField” as the index?
Currently I create an empty OrderedMap, then iterate over my parsed data, and set them one by one within a withMutations
. It doesn’t feel intuitive, what do you think?
Thank you in advance.
Issue Analytics
- State:
- Created 9 years ago
- Comments:28
So you’re looking to maintain the order of this array of records but also have the ability to look up each one by id. Then yes, OrderedMap is what you want, but of course OrderedMap expects key/value pairs, not just an array.
Here’s one way to do it - building up the OrderedMap manually. Let’s call your posted data,
var data = [...];
.First, let’s show how we would do this very simply, but not yet efficiently:
The problem here is that we’re creating a whole new Map for every set. Because of structural sharing this isn’t as bad as it would be if we were really cloning the whole data structure, but we can still do better since we want to think of this as “one operation”. You’re idea to use
withMutations
is the right one!This will be very performant, as it only ever creates a single map data structure.
Note that we had to use forEach and side effects to perform this task. That’s really just perfectly fine, but if we wanted to do this in a more pure function style, we could use Sequence operations:
This is a nice one-liner. It’s almost exactly the same “under the hood” as the previous example using forEach.
mapKeys
to replace the array’s indices with theid
property of the record that we want for our OrderedMap. Then wemap
the JS object values to Immutable Maps, then we turn that lazy sequence into a concrete structure - our OrderedMap.Resurrecting: isn’t something like this more readable and faster:
Immutable.OrderedMap(data.map(o => [o.id, Immutable.Map(o)]))
http://jsperf.com/immutable-ordered-map-construction