Reputation: 386
I'm starting to use immutable.js and don't understand why get method of Sets doesn't show the same result as the get method from Lists
import { fromJS, List, Map, Set } from 'immutable';
const things = fromJS(
[
{
id: 9,
nome: 'nove'
},
{
id: 7,
nome: 'sete'
},
{
id: 8,
nome: 'oito'
},
{
id: 8,
nome: 'oito'
}
]
).toSet();
const moreThings = fromJS(
[
{
id: 9,
nome: 'nove'
},
{
id: 6,
nome: 'seis'
}
]
).toSet();
const anotherThing = Map(
{
id: 4,
nome: 'quatro'
}
);
const allThingsSorted = things
.union(moreThings)
.add(anotherThing)
.sortBy(thing => thing.get('id'));
console.log(allThingsSorted); // [Object, Object, Object, Object, Object]
console.log(allThingsSorted.get(1)); // undefined
console.log(allThingsSorted.toList().get(1)); // {id: 6, nome: "seis"}
I expected the second log undefined
to be equal to the third log {id: 6, nome: "seis"}
.
What should I do to get the expected result, instead of converting to List?
Upvotes: 0
Views: 542
Reputation: 5019
A list is like a shelf, where you put books besides each other. Each book is in a (sometimes randomly) sorted order and can be referenced by its position (index). You can say "I want to read the 2nd book from the left".
A set on the other hand is a box full of assorted books. Its an chaotic storage, where books have no position/index (!). You can check the box wheter it contains a specific book, but not say where the book exactly is.
The key of a book in a Set is the book itself! You can only call get
on it when you have a reference to the book already, making the method completly useless.
This concept is valid for Set in general, not just immutable. The JavaScript native Set does not even have a get
, it only has a has
method. Immutable has all these methods on the Set because it uses the Collection interface on all collection types.
Not all of these methods make sense. Furthermore, the description in the docs might be misleading sometimes, as it often is derived from the parent class.
Sets are useful when you only need to check wheter your list contains an object or not. Lists on the other hand are for when you need an ordered collection and need to be able to get an object by it's index.
The collection types of Immutable can be easily converted to an other collection type. You already figured this out, as you merged a Set with a List. Note that allThingsSorted = things.union(moreThings)
results in a Set, as the object on which you call union
defines the type.
If you need to have indexes on a Set, use OrderedSet! You can call toIndexedSeq()
on it to get an iterable list, where you can get
by index
Upvotes: 1
Reputation: 13393
List.get
get's an element by its index in the list, so .get(1)
returns the second element (which is the one with id:6 after sorting).
Set.get
will get an element by its id, so .get(1)
looks for an element with id:1 which it doesn't find
Upvotes: 2