tc39 / proposal-policy-map-set

A TC39 proposal for Maps and Sets with cache replacement policies like LRU and LFU.
BSD 3-Clause "New" or "Revised" License
15 stars 2 forks source link

Consider CacheMap and CacheSet as a third alternative? #8

Open jasonwilliams opened 2 years ago

jasonwilliams commented 2 years ago

Having Cache in the name makes it very obvious and easy for users to know "this is a Map but for caching" (likewise for set). Rather than having the policy name in the class. It also allows for extending policies in future without saturating the scope.

I also think this is clearer than extending Set with extra arguments. Showing explicit usage of Cache in the source code makes it easier for users to see the use-case.

Some examples

const cache = new CacheMap(maxNumOfEntries, 'lifo', entries = []);
const cache = new CacheSet(maxNumOfEntries, 'lifo', values = []);
const cache = new CacheMap(maxNumOfEntries, 'fifo', entries = []);
const cache = new CacheSet(maxNumOfEntries, 'fifo', values = []);
const cache = new CacheMap(maxNumOfEntries, 'lru', entries = []);
const cache = new CacheSet(maxNumOfEntries, 'lru', values = []);
ljharb commented 2 years ago

Or, what about class CacheMap extends Map etc, but passing the extra arguments into the super constructor?

Then the generic case is covered, and the common case would use the subclasses.

js-choi commented 2 years ago

See also #1 and #5.

I think this an entirely viable API. In fact, I prefer it to the LIFOMap/LIFOSet/etc. system we have right now. (I’d love to hear opinions from the other champions too before making a pull request on the explainer.)

Also, if we go with this, we probably should rename the proposal to proposal-caches or proposal-cache-map-set.

Also, I think I would prefer to put the policy type before the cardinality/trigger, like:

new CacheMap('lifo', 256, entries)
js-choi commented 2 years ago

A problem with using enumerated string constants for policies is that it disallows custom policies. An alternative approach would be to make CacheMap an abstract class whose hooks are given to the constructor, and with specific built-in policies also being subclasses. I spun this problem off into #11.