The trimCache function in Going Offline
Paul Yabsley wrote to let me know about an error in Going Offline. It’s rather embarrassing because it’s code that I’m using in the service worker for adactio.com but for some reason I messed it up in the book.
It’s the trimCache
function in Chapter 7: Tidying Up. That’s the reusable piece of code that recursively reduces the number of items in a specified cache (cacheName
) to a specified amount (maxItems
). On page 95 and 96 I describe the process of creating the function which, in the book, ends up like this:
function trimCache(cacheName, maxItems) {
cacheName.open( cache => {
cache.keys()
.then( items => {
if (items.length > maxItems) {
cache.delete(items[0])
.then(
trimCache(cacheName, maxItems)
); // end delete then
} // end if
}); // end keys then
}); // end open
} // end function
See the problem? It’s right there at the start when I try to open cache like this:
cacheName.open( cache => {
That won’t work. The open
method only works on the caches
object—I should be passing the name of the cache into the caches.open
method. So the code should look like this:
caches.open( cacheName )
.then( cache => {
Everything else remains the same. The corrected trimCache
function is here:
function trimCache(cacheName, maxItems) {
caches.open(cacheName)
.then( cache => {
cache.keys()
.then(keys => {
if (keys.length > maxItems) {
cache.delete(keys[0])
.then(
trimCache(cacheName, maxItems)
); // end delete then
} // end if
}); // end keys then
}); // end open then
} // end function
Sorry about that! I must’ve had some kind of brainfart when I was writing (and describing) that one line of code.
You may want to deface your copy of Going Offline by taking a pen to that code example. Normally I consider the practice of writing in books to be barbarism, but in this case …go for it.
This was originally posted on my own site.