jonaskello / tslint-immutable

TSLint rules to disable mutation in TypeScript.
MIT License
417 stars 14 forks source link

Question: cannot use reduce on array with initial = `[]` and no-array-mutation #146

Closed tomsquest closed 5 years ago

tomsquest commented 5 years ago

Given "no-array-mutation": [true, "ignore-new-array"] Given tslint-immutable": "6.0.1" When using the following code:

myArray.reduce((acc, item) => {
      // stuff here

      acc.push( item );
      return acc;
    }, []);

Then a linting error is returned Mutating an array is not allowed..

What is the appropriate way to push to a "local" array (the accumulator) with no-array-mutation enabled?

RebeccaStevens commented 5 years ago

Try this code:

myArray.reduce((acc, item) => {
  // stuff here

  return [
    ...acc,
    item
  ];
}, []);
tomsquest commented 5 years ago

Yeah, that what I used. I thought that tslint-immutable could let a local array be pushed (even if the accumulator is not really local).

Is this different from ignore-local (which is not available on no-array-mutation ?

RebeccaStevens commented 5 years ago

All though I agree that being able to mutate an array locally makes sense in the example you gave, there is no easy way to detect the difference between that use case and a general use case.

The reason ignore-local isn't available for this rule is because pretty much every use of an array is local - It's not that often that you would use an array outside of a function.

tomsquest commented 5 years ago

Thanks @RebeccaStevens. No problem, and spreading the array is very similar.