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

Add a getOrSet() convenience method to delegate memoization / lazy initialization to the cache #335

Open
0x24a537r9 opened this issue Apr 26, 2024 · 0 comments

Comments

@0x24a537r9
Copy link

When using this package for memoization / lazy initialization, there's a pretty common pattern for getting while also setting only if a value is not already set:

function getValue(key) {
  const cachedValue = cache.get(key);
  if (cachedValue !== undefined) return cachedValue; // Should this actually be using .has(key)? That would then require another .get() call if so...

  const newValue = someExpensiveFunction();
  cache.set(key, newValue);
  return newValue;
}

It seems to me that it's common enough (and subtle enough when it comes to checking null vs. undefined vs. using .has()) that it would be worthwhile to define a function like getOrSet:

function getValue(key) {
  return cache.getOrSet(key, () => expensiveFunction());
}

Apart from the convenience factor, this would put the burden of correctness when it comes to existence checking (which I suspect might actually incorrect above in the case of cached values of undefined) on this library's maintainers (who are much more qualified than the average user of this this package to know the safest behavior), and also might open an opportunity for slight optimization if the correct behavior is .has(), since without access to the internal state of the cache one would have to also add a .get() after the .has(), adding more function invocations and another lookup.

If this were deemed something worthwhile to add, the question is whether to have it be an independent function or an option in the options for get. E.g. it could be a new getOrSet or getWithDefault or memoize method, or a getDefault: () => T option for get. I think a new method avoids a) potentially dangerously unexpected/misunderstood behavior where it ends up performing a write operation when .get() sounds like it would only be a read operation, and B) it being buried in options documentation, leading to less use.

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

No branches or pull requests

1 participant