Skip to content

Commit

Permalink
feat(plugin): allow some one-line arrow functions
Browse files Browse the repository at this point in the history
  • Loading branch information
zanminkian committed Apr 17, 2023
1 parent e28861a commit da5ba54
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 1 deletion.
Expand Up @@ -17,15 +17,38 @@ const valids = [
// allow export default
'export default () => {}',
'export default defineConfig(() => {})',
'const foo = (x, y) => x + y',
'const foo = (x) => `x: ${x}`',
'const foo = () => \'hello\'',
'const foo = () => 123',
'const foo = () => false',
'const foo = () => /abcd/',
'const foo = () => undefined',
'const foo = () => null',
'const foo = () => String(123)',
'const foo = async (x, y) => x + y',
'const foo = async (x) => `x: ${x}`',
'const foo = async () => \'hello\'',
'const foo = async () => 123',
'const foo = async () => false',
'const foo = async () => /abcd/',
'const foo = async () => undefined',
'const foo = async () => null',
'const foo = async () => String(123)',
// 'const foo = () => ({a: 123})', // Not sure that one-line object expression is valid
]

const invalids = [
[
'const foo = (x, y) => \nx + y',
'function foo (x, y) {\n return x + y\n}',
],
[
'const foo = (as: string, bar: number) => { return as + bar }',
'function foo (as: string, bar: number) { return as + bar }',
],
[
'const foo = <K, T extends Boolean>(as: string, bar: number): Omit<T, K> => as + bar',
'const foo = <K, T extends Boolean>(as: string, bar: number): Omit<T, K> => \nas + bar',
'function foo <K, T extends Boolean>(as: string, bar: number): Omit<T, K> {\n return as + bar\n}',
],
[
Expand Down
11 changes: 11 additions & 0 deletions packages/eslint-plugin-antfu/src/rules/top-level-function.ts
Expand Up @@ -40,6 +40,17 @@ export default createEslintRule<Options, MessageIds>({
return
if (declaration.id.typeAnnotation)
return
if (
[
'BinaryExpression',
'Literal',
'TemplateLiteral',
'Identifier',
'CallExpression',
].includes(declaration.init?.body.type)
&& declaration.id?.loc.start.line === declaration.init?.body.loc.end.line
)
return

const arrowFn = declaration.init
const body = declaration.init.body
Expand Down

0 comments on commit da5ba54

Please sign in to comment.