diff --git a/src/rules/immutable-data.ts b/src/rules/immutable-data.ts index 91e59f243..cac723773 100644 --- a/src/rules/immutable-data.ts +++ b/src/rules/immutable-data.ts @@ -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", @@ -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. */ @@ -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; diff --git a/tests/rules/immutable-data/ts/array/valid.ts b/tests/rules/immutable-data/ts/array/valid.ts index 24ef98692..3ca049855 100644 --- a/tests/rules/immutable-data/ts/array/valid.ts +++ b/tests/rules/immutable-data/ts/array/valid.ts @@ -330,6 +330,14 @@ const tests: Array>> = [ `, optionsSet: [[{ ignoreImmediateMutation: true }]], }, + { + code: dedent` + "foo".split("").sort(); + const bar = "bar"; + bar.split("").sort(); + `, + optionsSet: [[{ ignoreImmediateMutation: true }]], + }, ]; export default tests;