George Mauer already provided a wonderful answer I totally agree with him. I have only one focus in this review and that is speed.
Your code is very slow/not very efficient right now, even though it may not totally seem like it. This is because you are interacting with localStorage
too much, and interacting with localStorage
can be slow (I mean, you are accessing this external memory bank for data perhaps many times).
An easy way to speed this up would be to store the local storage in this object itself. To do this, you could create an init method that simply copies local storage into the object:
init: function() {
for(var key in localStorage) {
if(localStorage.hasOwnProperty(key)) {
this.storage[key] = localStorage[key];
}
}
}
Then, when called, will go through local storage, taking all of it's data and copying it into this storage
object (you can call it something else). Now, instead of accessing localStorage when looking for and setting data, we can use this.storage
:
get: function(key) { return this.storage[key]; }
set: function(key, val) { this.storage[key] = val; }
This code will be much faster now because rather than constantly accessing local storage, you can access this local object instead.
Of course, this data will not be stored when the browser closes, so another method is needed to save this data back to local storage. You can call this save
:
save: function() {
... copy this.storage data into localStorage ...
}
As was pointed out to me, this could potentially slow the heck out of a program when first initialized if the storage contains a lot of data.
As a simple fix, you can have have the init
method take an optional parameter of which data to take over in the form of keys:
init: function(keys) {
...
// if keys was supplied and this current key is in the list of keys to take
if(keys !== undefined && keys.indexOf(key) !== -1) {
this.storage[key] = localStorage[key];
}
}
This should be good enough. However, if you want to go a step further, you can also have another optional parameter for specifying how much data to read in. Ex: 1500 bytes.
This would be much more complicated. For every piece of data you read in, you would have to read how big that data is and add it to a total data size counter. Then, once you read too much, you'll have to trim down data from the last read you just did.
I don't have time to cook up an example now, but you might be able to come up with this on your own.