Skip to content

Make .get always return a value, even if it is expired#56

Closed
TehShrike wants to merge 1 commit intoavoidwork:masterfrom
trex-arms:2022-10-27-fix-issue-where-get-doesnt-always-return-something-like-youd-expect
Closed

Make .get always return a value, even if it is expired#56
TehShrike wants to merge 1 commit intoavoidwork:masterfrom
trex-arms:2022-10-27-fix-issue-where-get-doesnt-always-return-something-like-youd-expect

Conversation

@TehShrike
Copy link
Copy Markdown

@TehShrike TehShrike commented Oct 27, 2022

This could be an issue instead of a pull request, you can consider this a discussion starter if you want.

I ran into an issue recently when doing this:

if (cache.has(key)) {
	const value = cache.get(key)
	// assume that value is a legit value
}

I ran into issues because cache.has will return true if the item is in the map, but then the call to cache.get would delete the item if it was expired and return undefined, and I would get runtime errors because I assumed that cache.has meant that I could safely call cache.get in the same tick.

This fixes an issue where you could

if (cache.has(key)) {
	const value = cache.get(key)
	// assume that value is a legit value
}

and have issues because cache.has will return true if the item is in the map, but then the call to .get would delete the item if it was expired and return undefined.
@avoidwork avoidwork closed this Oct 28, 2022
@avoidwork
Copy link
Copy Markdown
Owner

avoidwork commented Oct 28, 2022

No, you should never call that method. it's not for you.

It's purposefully absent from the README.md.

@TehShrike
Copy link
Copy Markdown
Author

Huh. I'm currently using tiny-lru as a drop-in replacement for native Map

@avoidwork
Copy link
Copy Markdown
Owner

avoidwork commented Oct 28, 2022

You should stop, it's not meant to do that. 'has()' is private because it's a duplicating statement within get() and set(); this lib has always had lazy expiration which works on get() ... so because something is in the items doesn't mean it's valid to use.

Every place i use this lib i generally assign the returned value and then do a conditional statement; if it's expired or not there i get the same return result.

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 this pull request may close these issues.

2 participants