arqex / freezer

A tree data structure that emits events on updates, even if the modification is triggered by one of the leaves, making it easier to think in a reactive way.
MIT License
1.28k stars 56 forks source link

Array splice lead to wrong result #76

Closed albertogasparin closed 8 years ago

albertogasparin commented 8 years ago

It looks like if you are manipulating an array with splice(), you might get the wrong result. Here I'm trying to move one item from position 0 to 1

var store = new Freezer({
    a: [{id: 1}, {id: 2}, {id: 3}],
});

var arrayA = store.get().a;
var firstA = arrayA[0];

arrayA.splice(0, 1);
arrayA.splice(1, 0, firstA);

store.on('update', function(){
  store.get().a; // is [{id: 2}, {id: 3}] 
});

I've also created a demo to replicate the issue. The code works as expected with native splice().

arqex commented 8 years ago

Hi Alberto,

When you do arrayA.splice(0, 1) you are updating the array in the freezer state and a new array is created inside freezer for that update, but arrayA is immutable, it doesn't change at all. After calling the first splice, arrayA is not in freezer anymore, so the second splice doesn't modify it.

You need to update the reference to the array in the freezer store:

arrayA = arrayA.splice(0, 1);
arrayA.splice(1, 0, firstA);

http://jsbin.com/likahaqere/1/edit?js,console

albertogasparin commented 8 years ago

Thanks for the quick reply. By better reading the docs I've found the statement where you explain this behaviour. I forgot that the methods, despite having the same name, behave differently from native ones. Cheers :+1: