From 35d44891f1f09422211e8e1b02db10db6e27a2a8 Mon Sep 17 00:00:00 2001 From: Ed S Date: Mon, 24 Jun 2024 11:36:55 +0100 Subject: [PATCH] Rule fix: `no-extend`: Only fix if first arg is object literal (#330) If the first argument is a variable which could be null or undefined, then Object.assign will throw. We could convert to `Object.assign( foo || {}, ... )` but in most cases this is unnecessary, so probably better to leave it to users to fix manually. --- docs/rules/no-extend.md | 1 + src/rules/no-extend.js | 4 +++- tests/rules/no-extend.js | 5 +++++ 3 files changed, 9 insertions(+), 1 deletion(-) diff --git a/docs/rules/no-extend.md b/docs/rules/no-extend.md index e324987..6b44442 100644 --- a/docs/rules/no-extend.md +++ b/docs/rules/no-extend.md @@ -27,6 +27,7 @@ $.extend( { myUtil: fn } ); ❌ Examples of **incorrect** code with `[{"allowDeep":true}]` options: ```js $.extend( {}, foo ); +$.extend( fooCouldBeNull, doesNotAutofix ); ``` ✔️ Examples of **correct** code with `[{"allowDeep":true}]` options: diff --git a/src/rules/no-extend.js b/src/rules/no-extend.js index 99f61b5..6addf21 100644 --- a/src/rules/no-extend.js +++ b/src/rules/no-extend.js @@ -48,7 +48,9 @@ module.exports = { node, message: 'Prefer Object.assign or the spread operator to $.extend', fix: function ( fixer ) { - if ( !isDeep ) { + // Only auto-fix if we are sure the first argument is an object. + // If it is undefined or null variable, then Object.assign will throw. + if ( !isDeep && node.arguments[ 0 ] && node.arguments[ 0 ].type === 'ObjectExpression' ) { return fixer.replaceText( node.callee, 'Object.assign' ); } } diff --git a/tests/rules/no-extend.js b/tests/rules/no-extend.js index dd04dd3..eb9b455 100644 --- a/tests/rules/no-extend.js +++ b/tests/rules/no-extend.js @@ -32,6 +32,11 @@ ruleTester.run( 'no-extend', rule, { options: [ { allowDeep: true } ], errors: [ error ], output: 'Object.assign({}, foo)' + }, + { + code: '$.extend(fooCouldBeNull, doesNotAutofix)', + options: [ { allowDeep: true } ], + errors: [ error ] } ] } );