-
Notifications
You must be signed in to change notification settings - Fork 1
/
jsdoc-check-optional-params.js
80 lines (66 loc) · 2 KB
/
jsdoc-check-optional-params.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
const doctrine = require("doctrine");
module.exports = {
meta: {
type: "suggestion",
docs: {
description: "Enforce style for optional parameters",
category: "Best Practices",
recommended: true,
}
},
create(context) {
function checkOptionalParams(node) {
// Get JSDoc comments
const jsDocComment = context.getSourceCode().getJSDocComment(node);
if (!jsDocComment) {
return;
}
// This rule assumes that function params and JSDoc params match \
// (enforced by jsdoc/require-param)
const parsed = doctrine.parse(jsDocComment.value, {
unwrap: true,
sloppy: true,
tags: ["param"]
});
const jsdocParams = parsed.tags;
let i = 0;
if (jsdocParams.length) {
node.params.forEach((param) => {
i = checkNode(param, jsdocParams, i);
});
}
function checkNode(node, jsdocParams, i) {
jsdocParam = jsdocParams[i];
if (!jsdocParam || !jsdocParam.type) {
context.report({
node,
message: "No matching JSDoc param found"
});
return;
}
if (node.type === "ObjectPattern") {
i++;
node.properties.forEach((property) => {
i = checkNode(property.value, jsdocParams, i);
});
return i;
} else if (node.type === "AssignmentPattern" && jsdocParam.type.type !== "OptionalType") {
context.report({
node,
message: "Optional parameters in JSDoc should be surrounded by brackets"
});
} else if (jsdocParam.type.type === "OptionalType" && node.type !== "AssignmentPattern") {
context.report({
node,
message: "Non-optional parameters in JSDoc should not be surrounded by brackets"
});
}
return i + 1;
}
}
return {
FunctionDeclaration: checkOptionalParams,
FunctionExpression: checkOptionalParams
};
}
};