marcuswestin / store.js

Cross-browser storage for all use cases, used across the web.
MIT License
14.02k stars 1.33k forks source link

forEach not working as expected #224

Closed dperezrada closed 5 years ago

dperezrada commented 7 years ago

When deleting or adding elements inside a foreach, or during the foreach. Is causing change in the length of the storage,

for (var index = 0; index < 100; index++) {
    store.set('k_'+index, index)
}
var found_elements = [];
store.forEach(function(key, val) {
    store.remove(key);
    found_elements.push(key);
});
console.log("Found elements:", found_elements.length);
//The output is: Found elements: 50

After this code runs, it leaves 50 elements (tested with localstorage).

Seen the implementation of localstorage, it's clear that this problem has to happen:

for (var i = localStorage().length - 1; i >= 0; i--) {
    var key = localStorage().key(i)
    fn(read(key), key)
}

Maybe it could be solve with this, but not sure if there are other reasons to not do this.

var curentState = localStorage();
for (var i = curentState.length - 1; i >= 0; i--) {
    var key = curentState.key(i)
    fn(read(key), key)
}

Thanks in advance, this is a great library.

dperezrada commented 5 years ago

I wrote a test to check if this was a problem in the current version. And I did a pull request with the test https://github.com/marcuswestin/store.js/pull/292 It seems that current version using each, doesn't have the problem when removing elements anymore.