I’m looking for a way to do in the browser what Memcached offers, i.e. ability to configure a size limit (e.g. the localStorage quota) and it will evict old items automatically to keep the cache under limit.
The benefit is no explicit deletions are ever needed, as long as the cache keys are versioned/timestamped. I’ve seen some libraries that do similar with a “number of items” limit, but size limit would be more useful to stay under the browser’s quota.
2
Answers
This cannot be implemented perfectly, because there are no guarantees about how browsers store the content of the local storage but a close-enough implementation can be created.
We can start from the fact that a string in JS is a 16-bit unsigned integer value (because everything is stored as string in the
localStorage
). This means we can easily get the size of any string in bytes withcontent.length * 16 / 8
.So now we only need to create a cache which tracks the size of the stored content and the size of the keys, it stores the content under.
A very primitive and naive implementation could be:
I haven’t implemented the functions for reading data, but because the keys are stored in an array you can easily implement a getMostRecent() or getNthRecent(position) or just a simple get(key) function.
The implementation is in Typescript if you are not familiar with it just ignore the unknown parts.
If you want to use a solution that already exists for this functionality then you can check out this library runtime-memcache implements
lru
and a few other caching schemes(mru
,timeout
) in javascript.It uses modified Doubly Linked List to achieve O(1) for
get
,set
andremove
.