Skip to content

Commit

Permalink
fix(immutable-data): handle immediate mutation of arrays generated fr…
Browse files Browse the repository at this point in the history
…om strings

fix #759
  • Loading branch information
RebeccaStevens committed Mar 11, 2024
1 parent ef33c6e commit b003d1c
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 1 deletion.
19 changes: 18 additions & 1 deletion src/rules/immutable-data.ts
Original file line number Diff line number Diff line change
Expand Up @@ -165,7 +165,7 @@ const objectConstructorMutatorFunctions = new Set([
]);

/**
* Object constructor functions that return a new array.
* Object constructor functions that return new objects.
*/
const objectConstructorNewObjectReturningMethods = [
"create",
Expand All @@ -180,6 +180,13 @@ const objectConstructorNewObjectReturningMethods = [
"values",
];

/**
* String constructor functions that return new objects.
*
* @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#Methods
*/
const stringConstructorNewObjectReturningMethods = ["split"];

/**
* Check if the given assignment expression violates this rule.
*/
Expand Down Expand Up @@ -393,6 +400,16 @@ function isInChainCallAndFollowsNew(
) {
return true;
}

// Check for: "".split("")
if (
stringConstructorNewObjectReturningMethods.some(
isExpected(node.object.callee.property.name),
) &&
getTypeOfNode(node.object.callee.object, context).isStringLiteral()
) {
return true;
}
}

return false;
Expand Down
8 changes: 8 additions & 0 deletions tests/rules/immutable-data/ts/array/valid.ts
Original file line number Diff line number Diff line change
Expand Up @@ -330,6 +330,14 @@ const tests: Array<ValidTestCaseSet<OptionsOf<typeof rule>>> = [
`,
optionsSet: [[{ ignoreImmediateMutation: true }]],
},
{
code: dedent`
"foo".split("").sort();
const bar = "bar";
bar.split("").sort();
`,
optionsSet: [[{ ignoreImmediateMutation: true }]],
},
];

export default tests;

0 comments on commit b003d1c

Please sign in to comment.