-
Notifications
You must be signed in to change notification settings - Fork 18
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
Preventing array mutations via standard methods #2
Comments
concat and slice are actually safe, since they create a new array. |
You are right, I didn’t put enough thoughts when I wrote this parenthesis :). Mozilla Developer Network actually have a list of mutating methods on array: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype#Mutator_methods |
Also note that other standard objects have the same problem, for instance: const a = new Date();
a.setHour(0);
const b = { hello: 'world' };
Object.assign(b, { hello: 'mars' });
const c = new Uint8Array([20, 5, 15]);
c.sort(); In this example “constant” variables |
I actually starting working on a similar plugin a while back, and implemented a |
That can cause issues with |
True, though I might venture to say that if you're using Immutable.js you probably wouldn't benefit from this plugin, as you'll be relying on the library to help prevent mutations, not a linter. |
Well quite the contrary, if you want to prevent mutations in your existing code base, you will probably want to detect use of |
I guess you do have a point. Is there any way to statically infer that it's an array without using typescript or flow? |
I’d like to suggest banning all ExpressionStatement (see full proposal in #4). This will catch: names.push('bar')
names.concat([' bar ']) // no point in evaluating this anyway But not: const namesWithBar = names.concat([' bar ']) // ok, bound to another variable
return namesWithBar // ok, returned However it can’t catch this: const newSize = names.push('baz') // maybe `no-unused-vars` can catch this
const newObject = Object.assign(oldObject, { foo: 'bar' }) // tough luck |
I agree that this should be the resolution. Any method name based prohibition is too brittle. |
As you are closing this issue, at least it would be good to document the mutations that won’t be caught in the README of the |
Looking at the implementation of the
no-mutation
rule, it seems that the following code wouldn’t be caught:I imagine than catching these mutations is somehow difficult as it requires some advanced type inference to understand that
names
is a JavaScript array andpush
(orconcat
,slice
, etc.) a method that is actually mutating the object. So I’m opening the thread to discuss this problem.The text was updated successfully, but these errors were encountered: