meduzen / cachemap

A key-value cache built upon the JavaScript `Map` object.
Do What The F*ck You Want To Public License
0 stars 0 forks source link

Cache with expiration or until a condition is met #4

Open meduzen opened 1 year ago

meduzen commented 1 year ago

One approach for both this and #6 could be to maintain a WeakMap Map dedicated to items metadata.

A Weakmap Map item could look like this:

This way, if I'm correct, when an item is removed from the CacheMap, it is automatically garbage collected from the WeakMap. We can’t use a WeakMap for this. See next comment.

meduzen commented 1 year ago

First approach

The usage could look like this, according to first (rather successful) experiment:

let cat = cache.rememberDuring('cat', 'Drich', 2000) // 'Drich'
cat = cache.rememberDuring('cat', 'Kisa', 200) // still 'Drich'

await setTimeout(200) // wait…

cat = cache.rememberDuring('cat', 'Pitch', 200) // 'Pitch', because previous entry has expired

For this, the place for metadata is another Map object. We can’t use WeakMap because it doesn’t accept strings as key. Each metadata entry should be an object containing an expiration Date.

Prospective work:

  1. [x] When a Date object is passed instead of an integer, the Date object becomes the expiration. But then the method shouldn’t be named rememberDuring.
  2. [x] Alternatively, a callback function could be used as “shouldUpdateTheCache condition” (when truthy). In that case, I have to check if a function can be stored in the metadata Map, and run on retrieval. (no need to check, it works 🥳).
  3. [x] Because of this, there is no need for a specific method: we could use remember and add with a 3rd parameter accepting either an integer (duration), either a Date (expiration moment) either a function (callback condition) (currently on hold, see #29).

This is at the time of writing all done in #10.

Second approach

At first sight, it will probably be more convenient to override most CacheMap inherited methods, in order to have control of what happens on item retrieval/modification. Gonna experiment this at some point.