Skip to content

Commit b003d1c

Browse files
fix(immutable-data): handle immediate mutation of arrays generated from strings
fix #759
1 parent ef33c6e commit b003d1c

File tree

2 files changed

+26
-1
lines changed

2 files changed

+26
-1
lines changed

src/rules/immutable-data.ts

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -165,7 +165,7 @@ const objectConstructorMutatorFunctions = new Set([
165165
]);
166166

167167
/**
168-
* Object constructor functions that return a new array.
168+
* Object constructor functions that return new objects.
169169
*/
170170
const objectConstructorNewObjectReturningMethods = [
171171
"create",
@@ -180,6 +180,13 @@ const objectConstructorNewObjectReturningMethods = [
180180
"values",
181181
];
182182

183+
/**
184+
* String constructor functions that return new objects.
185+
*
186+
* @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#Methods
187+
*/
188+
const stringConstructorNewObjectReturningMethods = ["split"];
189+
183190
/**
184191
* Check if the given assignment expression violates this rule.
185192
*/
@@ -393,6 +400,16 @@ function isInChainCallAndFollowsNew(
393400
) {
394401
return true;
395402
}
403+
404+
// Check for: "".split("")
405+
if (
406+
stringConstructorNewObjectReturningMethods.some(
407+
isExpected(node.object.callee.property.name),
408+
) &&
409+
getTypeOfNode(node.object.callee.object, context).isStringLiteral()
410+
) {
411+
return true;
412+
}
396413
}
397414

398415
return false;

tests/rules/immutable-data/ts/array/valid.ts

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -330,6 +330,14 @@ const tests: Array<ValidTestCaseSet<OptionsOf<typeof rule>>> = [
330330
`,
331331
optionsSet: [[{ ignoreImmediateMutation: true }]],
332332
},
333+
{
334+
code: dedent`
335+
"foo".split("").sort();
336+
const bar = "bar";
337+
bar.split("").sort();
338+
`,
339+
optionsSet: [[{ ignoreImmediateMutation: true }]],
340+
},
333341
];
334342

335343
export default tests;

0 commit comments

Comments
 (0)