eslint-plugin-immutable
eslint-plugin-immutable copied to clipboard
New rule: no-mutating-assign
Description:
Warns when Object.assign
is used with the first parameter anything else than object initialisation.
Will warn:
const foo = {};
Object.assign(foo, {bar: 'BAR'});
Will not warn:
const foo = {};
Object.assign({}, foo, {bar: 'BAR'});
I initially thought this was a good idea too. But maybe a better idea is to implement #4 and then all uses of Object.assign() would be banned (as it does not return a value). Instead we could use spread syntax (as suggested in the readme).
const foo = {foo: 'FOO'}
const bar = {...foo, {bar: 'BAR'}}
Object.assign
does return a value - the first argument. In addition, spread syntax is not yet standard - it's only stage 1.
I would love this rule, as we use Object.assign({}, …)
all the time, but never want the first argument to be anything but a new empty object.
@ljharb: Actually I think object spread operator is at stage 2.
Seeing as there is no maintenance of the plugin, I've written my own that has this rule.
@jfmengels Would you say your plugin prevents every form of mutation?
@robinchew No, far from it.
I don't think there is any way to do that using ESLint as you simply often don't have enough information to tell whether a function or method is mutating the object or its parameters. I think you'd get a lot more useful information with TypeScript or Flow and information about external libraries.
For instance, no way to know that array.remove()
is mutating while R.remove()
from Ramda or Lodash/FP doesn't if you don't have more context on what the value of array
is. You could either forbid the use of remove methods and have lots of false positives, or only do it when you're sure you're handling an array, but then you'd have lots of missing cases.
That said, my plugin adds a few rules that lessen the number of possible mutations, some of which have been proposed here. But as no PRs has been merged and no release have been made since v1, I decided to "fork" this with improved quality (tests), and some additional rules for writing FP programs that I wanted to write anyway.
Hope this helps :)