How do i sort (swap) items inside an Immutable Map

2019-06-09 23:31发布

问题:

I want to swap items inside an immutable list within a Map, example:

const Map = Immutable.fromJS({
    name:'lolo',
    ids:[3,4,5]
});

i am trying to use splice to do the swapping, also tried with insert() an Immutable method.

Lets say i want to swap from [3, 4, 5] to [3, 5, 4], i am truing something like this:

list.set('ids', list.get('ids').splice(2, 0, list.get('ids').splice(1, 1)[0])

What's the best way to sort elements inside an Immutable data structures with Immutable.js ?

回答1:

You should use Map.update() and List.withMutations() for that matter:

map.update('ids', idsList => idsList.withMutations(function (idsList) {
    let temp = idsList.get(2);
    return idsList.set(2, idsList.get(1)).set(1, temp);
}));

Notice that I renamed your list to map - this is actually a Map.

And for simple sorting go for

map.update('ids', idsList => idsList.sort(function (a, b) {
    // magic
});


回答2:

Parametrized:

function swap(map, key, from, to) {
    return map.update(key, list => list.withMutations(list => {
        let soruce = list.get(from);
        let destination = list.get(to);
        return list.set(to, soruce).set(from, destination);
    }));
}


回答3:

You can use destructuring assignment to swap values at different indexes of array

const list = Immutable.fromJS({name:'lolo',ids:[3,4,5]});

[list._root.entries[1][1]._tail.array[1], list._root.entries[1][1]._tail.array[2]] = [
  list._root.entries[1][1]._tail.array[2]
  , list._root.entries[1][1]._tail.array[1]
];

console.log(list.get("ids").toArray());

plnkr http://plnkr.co/edit/ZcEFNIFTnji3xxs7uTCT?p=preview