Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

getOrCreate() method #102

Closed
rstacruz opened this issue Feb 12, 2017 · 3 comments · Fixed by #214
Closed

getOrCreate() method #102

rstacruz opened this issue Feb 12, 2017 · 3 comments · Fixed by #214

Comments

@rstacruz
Copy link

rstacruz commented Feb 12, 2017

This seems like a very common use case, and in fact it's the preferred way you use a cache in Rails. Is there any reason it's not implemented?

cache.getOrCreate(key, () => { expensive computation })

Where:

LRU.prototype.fetch = function (key, fn) {
  if (this.has(key)) return this.get(key)
  var result = fn()
  this.set(key, result)
  return result
}
@airliti
Copy link

airliti commented Nov 16, 2017

Not implementing a .getOrCreate method could even be a possible issue ( and as demonstrated with your implementation )! The timing between the #.has and #.get method could be just surpassing the maxAge resulting in an undefined value. I did an implementation for an LruCache for myself and a possible solution can be found through visiting https://github.com/airliti/estructura/blob/master/src/lib/LruCache.js#L457.

If your interested, I've got sample code to prove the problem.

@isaacs
Copy link
Owner

isaacs commented Feb 8, 2022

I'd accept a fetch method like you describe.

I'm not worried about the time resolution of TTL expiring, this is primarily a lru cache anyway.

@isaacs
Copy link
Owner

isaacs commented Mar 15, 2022

Proof of concept if anyone wants to pick this up and write tests for it: https://github.com/isaacs/node-lru-cache/blob/isaacs/get-or-fetch-return-stale-while-fetching/index.js

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants