kwiwk/lru-cached-getter

node v8.17.0
version: 2.0.0
endpointsharetweet
An example of using the LRUCachedGetter!
First we define some async helpers.
async function delayMs(ms) { return new Promise(resolve => setTimeout(resolve, ms)); } // Return how long the async function takes to resolve in milliseconds async function benchmarkMs(func) { const before = Date.now(); await func(); const after = Date.now(); return after.valueOf() - before.valueOf(); }
Import & Create our LRUCachedGetter
const { LRUCachedGetter } = require("@kwiwk/lru-cached-getter"); const lru = new LRUCachedGetter({ getter: async(ms) => { await delayMs(ms); return ms; }, hasher: ms => ms.toString(), maxSize: 100 });
Get a value for the first time. The value is retrieved through the cache's getter.
let ms = await benchmarkMs(async() => { const val = await lru.get(1000); console.log(`Value: ${val}`); }); console.log(`Time: ${ms}ms`);
Get the value a second time. The value is retrieved through the cache itself.
ms = await benchmarkMs(async() => { const val = await lru.get(1000); console.log(`Value: ${val}`); }); console.log(`Time: ${ms}ms`);
Loading…

no comments

    sign in to comment