Skip to content

lru cache

Created: 2020-09-09 09:30:04 -0700 Modified: 2020-09-09 09:30:41 -0700

Code to serialize and deserialize an LRU

Section titled Code to serialize and deserialize an LRU

Note: I wrote this for Bot Land and didn’t know if it would come in handy in the future, so here it is:

/**
* This file exists because the Node module "lru-cache" has dump/load functions,
* but it won't serialize/deserialize the objects in the LRU for me, so I've
* replaced it with serializeLru and deserializeLru.
*/
const LRU = require('lru-cache');
const _ = require('lodash');
/**
* Serializes an LRU as long as each entry has a "serialize" function on it.
* @param {LRU} lru
* @return {Array<Object>} - serialized entries that have 'k' and 'v' properties
*/
function serializeLru(lru) {
const serializedEntries = [];
lru.rforEach((value, key, cache) => {
serializedEntries.push({
k: key,
v: value.serialize(),
});
});
return serializedEntries;
}
/**
* The converse of serializeLru.
* @param {Array<Object>} serializedLruEntries - the return value from
* serializeLru
* @param {Function} deserializationFn - the function to use to deserialize
* each entry
* @param {number} maxEntries - the max number of entries to have in the new
* LRU
* @return {LRU}
*/
function deserializeLru(serializedLruEntries, deserializationFn, maxEntries) {
const lru = new LRU({
max: maxEntries,
});
_.forEach(serializedLruEntries, (serializedEntry) => {
lru.set(serializedEntry.k, deserializationFn(serializedEntry.v));
});
return lru;
}
module.exports = {
serializeLru,
deserializeLru,
};