Created
October 22, 2024 10:28
-
-
Save mitchellwarr/72639ce64c371ba4459220b5eef02a0e to your computer and use it in GitHub Desktop.
Eslint function-multiline-arguments
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module.exports = { | |
rules: { | |
'function-multiline-arguments': { | |
meta: { | |
type: 'layout', | |
fixable: 'code', | |
schema: [] // no options | |
}, | |
create: context => ({ | |
CallExpression: node => { | |
if (node.arguments.length <= 1) return; | |
let startLine = node.callee.loc.end.line; | |
let endLine = node.loc.end.line; | |
if (startLine == endLine) return; | |
let argLines = node.arguments | |
.flatMap( | |
node => node.loc.start.line == node.loc.end.line | |
? [node.loc.start.line] | |
: [node.loc.start.line, node.loc.end.line] | |
); | |
let endsInFunction = !!node.arguments[node.arguments.length -1].body; | |
if (new Set(argLines.slice(0, -1)).size == 1 && endsInFunction) return; | |
argLines.push(startLine); | |
argLines.push(endLine); | |
if (new Set(argLines).size == argLines.length) return; | |
context.report({ | |
node, | |
message: 'Function arguments covering multiple lines should each start on a new line', | |
fix(fixer) { | |
let actions = []; | |
node.arguments.forEach( | |
(arg, i, arr) => { | |
let prev = i == 0? startLine : arr[i-1].loc.end.line; | |
if (arg.loc.start.line == prev) { | |
actions.push(fixer.insertTextBefore(arg, '\n')); | |
} | |
} | |
); | |
let lastArg = node.arguments[node.arguments.length -1]; | |
if (lastArg.loc.start.line == endLine) { | |
actions.push(fixer.insertTextAfter(lastArg, '\n')); | |
} | |
return actions; | |
} | |
}); | |
} | |
}) | |
} | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment