Search code examples
javascriptsessionstorage

limit sessionStorage to x entries


i am using html5 sessionStorage like a psuedo javascript console so i can retrieve errors that have previously been recorded there. i'm trying to limit the number of entries in sessionStorage so i don't end up with thousands of entries by deleting the oldest entries as the maximum number of entries is exceeded.

I've written the following javascript code but it doesn't work - it's not deleting entries when the maximum count is exceeded.

maxlen=100;
sessionlen=window.sessionStorage.length; // this returns the correct count
if(sessionlen>maxlen){
    difference=sessionlen-maxlen; // this returns the correct difference
    for(i=0;i<difference;i++){
        window.sessionStorage.removeItem(0); // this isn't happening
    }}

i'm probably missing something really simple. can anyone help?


Solution

  • You have to imagine that sessionStorage is a dictionary where each value is mapped by a key, if you want to remove the oldest entries once the maximum count is exceeded you have to map to data like a queue, a queue is easily implemented in JavaScript with an array (push with Array.prototype.push() and pop with Array.prototype.shift), however your ids are not exactly mapped to the indexes of the array (the id can be anything) so how about using another data structure to hold the order of the id's that you're saving? Let's call the temporal structure idQueue, whenever the maximum capacity or whatever you need to limit the size of this array is reached you just pop it, i.e. use .shift. Since this needs to be replicated in the sessionStorage structure each operation (push and pop) is done on the two structures:

    var limit = 10;
    var idQueue = [];
    
    function pushToStorage(id, value) {
      idQueue.push(id);
      window.sessionStorage.setItem(id, value);
    }
    
    function popFromStorage() {
      var oldest = idQueue.shift();
      window.sessionStorage.removeItem(oldest);
    }
    
    function checkLength() {
      while (idQueue.length > limit) {
        popFromStorage();
      }
    }