sindresorhus/on-change

Omit reIndexing of arrays when methods like unshift or splice are used

Baumgaer opened this issue · 1 comments

When on-change observes an array which is modified with unshift (or other methods which are able to insert or delete items somewhare alse than the end of the array) the handler will be fired for each re-index. similar to #56

Example:

const myObservedArray = onChange([1, 2, 3, 4, 5], (path, newVal, oldVal) => {
    console.log(path, newVal, oldVal);
});
myObservedArray.unshift(6);

The output will be:

path newVal oldVal comment
5 5 undefined because unshift starts first to move every item one index further and overwrites existing values with the beginning at the end
4 4 5
3 3 4
2 2 3
1 1 2
0 6 1 the origin unshift

There should be an option to avoid this behavior and only yield the origin change to the listener function. Maybe you could add an aditional parameter to the function, named "action" or something like that, to be able to determine what happened really.

I can't replicate your issue. I only see one call to the listener function. I am working on #48 right now though, which will improve performance on specific methods.