Skip to content

Instantly share code, notes, and snippets.

@metaory
Last active January 9, 2024 08:42
Show Gist options
  • Select an option

  • Save metaory/2cc72ca1a46fcfc1900735f69008bfca to your computer and use it in GitHub Desktop.

Select an option

Save metaory/2cc72ca1a46fcfc1900735f69008bfca to your computer and use it in GitHub Desktop.
WeakMap Cache
const { log } = console;
const TTL_MN = 5 // mintes
const TTL_MS = TTL_MN * 60 * 1_000 // milliseconds
const MapRefs = new Map();
const Maps = new WeakMap();
function fetchStuff(someId) {
const ref = MapRefs.get(someId);
const map = Maps.get(ref);
const expired = Date.now() - (map?.ts ?? 0) > TTL_MS
if (!map || expired) {
const data = { name: "foo_" + someId }; // fake api call
MapRefs.set(someId, Symbol(someId));
Maps.set(MapRefs.get(someId), { data, ts: Date.now() });
return { ...data, DEBUG: "FETCH" };
}
return { ...map.data, DEBUG: "CACHE" };
}
log('one one', fetchStuff(11)); // one one { name: 'foo_11', DEBUG: 'FETCH' }
log('one one', fetchStuff(11)); // one one { name: 'foo_11', DEBUG: 'CACHE' }
log('...') // ...
log('two two', fetchStuff(22)); // two two { name: 'foo_22', DEBUG: 'FETCH' }
log('two two', fetchStuff(22)); // two two { name: 'foo_22', DEBUG: 'CACHE' }
log('two two', fetchStuff(22)); // two two { name: 'foo_22', DEBUG: 'CACHE' }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment