-
-
Notifications
You must be signed in to change notification settings - Fork 387
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
Rule proposal: Help with memoization #1864
Comments
We could make a rule where you give it a list of method names where you want the function to be pure. |
I don’t think that’s possible though. Can I use fetch in a pure function? I think it’s difficult to tell apart the inputs (location.hash) from the output (the server response via fetch). Both are technically accessing “global state” |
@fregante Then you would have to use an ignore comment for |
Makes sense, but also: 1 first commit// eslint-disable-next-line pure-memoization -- fetch is ok
const api = mem((name) => fetch(`/api/${name}`)) 2 add default// eslint-disable-next-line pure-memoization -- fetch is ok
const api = mem((name = document.title) => fetch(`/api/${name}`)) |
That is not specific to this rule though. You can accidentally disable more than you intended with any rule. It's also not a realistic example. |
I agree with your last point regarding "making an explicit choice" See these for a realistic example and the bugfix PR that such a rule would have prevented. Plenty of other such bugs in RG:
Another example where global/local scope should be blocked: serialized functions. There's a slight difference though
|
Probably impossible or too difficult or too complex for unicorn:
I thought about potentially enabling this rule on specific files, maybe enforcing only Maybe a rule that blocks any globals (except stuff like |
I think the only possible helper for memoized functions would be a rule to block default parameters, to be enabled on-demand: // eslint-enable-next-line unicorn/no-defaults
const api = mem((name = location.hash.replace('#','')) => fetch(`/api/${name}`))
// ^ Error: Default value not allowed
api()
api('contacts') |
Description
Memoized functions rely on their arguments to work properly. Using global state means you also have to remember using the same global state in
cacheKey
.Thoughts on how this can be avoided?
Fail
Pass
Additional Info
This is probably impossible to actually achieve in a linter though 🥲
Related:
The text was updated successfully, but these errors were encountered: