Skip to content

Commit 663f59e

Browse files
authored
feat: detect implicit return and fix nested return false positive. Closes #148
Detect implicit return and fix nested return false positive. Closes #148
2 parents 07212ab + f954528 commit 663f59e

File tree

2 files changed

+100
-1
lines changed

2 files changed

+100
-1
lines changed

src/rules/requireReturns.js

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,30 @@ export default iterateJsdoc(({
1414

1515
const sourcecode = utils.getFunctionSourceCode();
1616

17-
if (JSON.stringify(jsdocTags) === '[]' && sourcecode.indexOf('return') >= 1) {
17+
// build a one-liner to test against
18+
const flattenedSource = sourcecode.replace(/\r?\n|\r|\s/g, '');
19+
20+
const startsWithReturn = '(\\)\\s?\\{return)';
21+
22+
const endsWithReturn = '(return.*\\})';
23+
24+
const implicitReturn = '(\\s?=>\\s?\\b.*)';
25+
26+
const implicitObjectReturn = '(\\s?=>\\s?\\(\\{)';
27+
28+
const matcher = new RegExp([
29+
startsWithReturn,
30+
endsWithReturn,
31+
implicitObjectReturn,
32+
implicitReturn
33+
].join('|'), 'gim');
34+
35+
const positiveTest = (flattenedSource.match(matcher) || []).length > 0;
36+
37+
const negativeTest = (flattenedSource.match(/(\{.*\{.*return)/gim) || []).length > 0 &&
38+
(flattenedSource.match(/(return)/gim) || []).length < 2;
39+
40+
if (JSON.stringify(jsdocTags) === '[]' && positiveTest && !negativeTest) {
1841
report('Missing JSDoc @' + targetTagName + ' declaration.');
1942
}
2043
});

test/rules/assertions/requireReturns.js

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,50 @@ export default {
1717
}
1818
]
1919
},
20+
{
21+
code: `
22+
/**
23+
*
24+
*/
25+
const foo = () => ({
26+
bar: 'baz'
27+
})
28+
`,
29+
errors: [
30+
{
31+
line: 2,
32+
message: 'Missing JSDoc @returns declaration.'
33+
}
34+
]
35+
},
36+
{
37+
code: `
38+
/**
39+
*
40+
*/
41+
const foo = bar=>({ bar })
42+
`,
43+
errors: [
44+
{
45+
line: 2,
46+
message: 'Missing JSDoc @returns declaration.'
47+
}
48+
]
49+
},
50+
{
51+
code: `
52+
/**
53+
*
54+
*/
55+
const foo = bar => bar.baz()
56+
`,
57+
errors: [
58+
{
59+
line: 2,
60+
message: 'Missing JSDoc @returns declaration.'
61+
}
62+
]
63+
},
2064
{
2165
code: `
2266
/**
@@ -62,6 +106,38 @@ export default {
62106
function quux () {
63107
}
64108
`
109+
},
110+
{
111+
code: `
112+
/**
113+
*
114+
*/
115+
function quux (bar) {
116+
bar.filter(baz => {
117+
return baz.corge();
118+
})
119+
}
120+
`
121+
},
122+
{
123+
code: `
124+
/**
125+
* @returns Array
126+
*/
127+
function quux (bar) {
128+
return bar.filter(baz => {
129+
return baz.corge();
130+
})
131+
}
132+
`
133+
},
134+
{
135+
code: `
136+
/**
137+
* @returns Array
138+
*/
139+
const quux = (bar) => bar.filter(({ corge }) => corge())
140+
`
65141
}
66142
]
67143
};

0 commit comments

Comments
 (0)