eslint-plugin-immutable icon indicating copy to clipboard operation
eslint-plugin-immutable copied to clipboard

New rule: no-mutating-assign

Open gajus opened this issue 8 years ago • 6 comments

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'});

gajus avatar May 01 '16 18:05 gajus

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'}}

jonaskello avatar May 01 '16 19:05 jonaskello

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 avatar May 01 '16 19:05 ljharb

@ljharb: Actually I think object spread operator is at stage 2.

jonaskello avatar May 04 '16 16:05 jonaskello

Seeing as there is no maintenance of the plugin, I've written my own that has this rule.

jfmengels avatar Jun 20 '16 23:06 jfmengels

@jfmengels Would you say your plugin prevents every form of mutation?

robinchew avatar Jul 19 '16 15:07 robinchew

@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 :)

jfmengels avatar Jul 19 '16 21:07 jfmengels