_id stringlengths 2 6 | title stringlengths 0 58 | partition stringclasses 3
values | text stringlengths 52 373k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q17800 | hasMetaDocsDescription | train | function hasMetaDocsDescription(metaPropertyNode) {
const metaDocs = getPropertyFromObject("docs", metaPropertyNode.value);
return metaDocs && getPropertyFromObject("description", metaDocs.value);
} | javascript | {
"resource": ""
} |
q17801 | hasMetaDocsCategory | train | function hasMetaDocsCategory(metaPropertyNode) {
const metaDocs = getPropertyFromObject("docs", metaPropertyNode.value);
return metaDocs && getPropertyFromObject("category", metaDocs.value);
} | javascript | {
"resource": ""
} |
q17802 | hasMetaDocsRecommended | train | function hasMetaDocsRecommended(metaPropertyNode) {
const metaDocs = getPropertyFromObject("docs", metaPropertyNode.value);
return metaDocs && getPropertyFromObject("recommended", metaDocs.value);
} | javascript | {
"resource": ""
} |
q17803 | getFirstNonSpacedToken | train | function getFirstNonSpacedToken(left, right, op) {
const operator = sourceCode.getFirstTokenBetween(left, right, token => token.value === op);
const prev = sourceCode.getTokenBefore(operator);
const next = sourceCode.getTokenAfter(operator);
if (!sourceCode.isSpaceBetweenTokens(prev, operator) || !sourceCode.isSpaceBetweenTokens(operator, next)) {
return operator;
}
return null;
} | javascript | {
"resource": ""
} |
q17804 | checkBinary | train | function checkBinary(node) {
const leftNode = (node.left.typeAnnotation) ? node.left.typeAnnotation : node.left;
const rightNode = node.right;
// search for = in AssignmentPattern nodes
const operator = node.operator || "=";
const nonSpacedNode = getFirstNonSpacedToken(leftNode, rightNode, operator);
if (nonSpacedNode) {
if (!(int32Hint && sourceCode.getText(node).endsWith("|0"))) {
report(node, nonSpacedNode);
}
}
} | javascript | {
"resource": ""
} |
q17805 | checkConditional | train | function checkConditional(node) {
const nonSpacedConsequesntNode = getFirstNonSpacedToken(node.test, node.consequent, "?");
const nonSpacedAlternateNode = getFirstNonSpacedToken(node.consequent, node.alternate, ":");
if (nonSpacedConsequesntNode) {
report(node, nonSpacedConsequesntNode);
} else if (nonSpacedAlternateNode) {
report(node, nonSpacedAlternateNode);
}
} | javascript | {
"resource": ""
} |
q17806 | checkVar | train | function checkVar(node) {
const leftNode = (node.id.typeAnnotation) ? node.id.typeAnnotation : node.id;
const rightNode = node.init;
if (rightNode) {
const nonSpacedNode = getFirstNonSpacedToken(leftNode, rightNode, "=");
if (nonSpacedNode) {
report(node, nonSpacedNode);
}
}
} | javascript | {
"resource": ""
} |
q17807 | isInRange | train | function isInRange(node, reference) {
const or = node.range;
const ir = reference.identifier.range;
return or[0] <= ir[0] && ir[1] <= or[1];
} | javascript | {
"resource": ""
} |
q17808 | getEncloseFunctionDeclaration | train | function getEncloseFunctionDeclaration(reference) {
let node = reference.identifier;
while (node) {
if (node.type === "FunctionDeclaration") {
return node.id ? node : null;
}
node = node.parent;
}
return null;
} | javascript | {
"resource": ""
} |
q17809 | updateModifiedFlag | train | function updateModifiedFlag(conditions, modifiers) {
for (let i = 0; i < conditions.length; ++i) {
const condition = conditions[i];
for (let j = 0; !condition.modified && j < modifiers.length; ++j) {
const modifier = modifiers[j];
let funcNode, funcVar;
/*
* Besides checking for the condition being in the loop, we want to
* check the function that this modifier is belonging to is called
* in the loop.
* FIXME: This should probably be extracted to a function.
*/
const inLoop = condition.isInLoop(modifier) || Boolean(
(funcNode = getEncloseFunctionDeclaration(modifier)) &&
(funcVar = astUtils.getVariableByName(modifier.from.upper, funcNode.id.name)) &&
funcVar.references.some(condition.isInLoop)
);
condition.modified = inLoop;
}
}
} | javascript | {
"resource": ""
} |
q17810 | report | train | function report(condition) {
const node = condition.reference.identifier;
context.report({
node,
message: "'{{name}}' is not modified in this loop.",
data: node
});
} | javascript | {
"resource": ""
} |
q17811 | registerConditionsToGroup | train | function registerConditionsToGroup(conditions) {
for (let i = 0; i < conditions.length; ++i) {
const condition = conditions[i];
if (condition.group) {
let group = groupMap.get(condition.group);
if (!group) {
group = [];
groupMap.set(condition.group, group);
}
group.push(condition);
}
}
} | javascript | {
"resource": ""
} |
q17812 | hasDynamicExpressions | train | function hasDynamicExpressions(root) {
let retv = false;
Traverser.traverse(root, {
visitorKeys: sourceCode.visitorKeys,
enter(node) {
if (DYNAMIC_PATTERN.test(node.type)) {
retv = true;
this.break();
} else if (SKIP_PATTERN.test(node.type)) {
this.skip();
}
}
});
return retv;
} | javascript | {
"resource": ""
} |
q17813 | toLoopCondition | train | function toLoopCondition(reference) {
if (reference.init) {
return null;
}
let group = null;
let child = reference.identifier;
let node = child.parent;
while (node) {
if (SENTINEL_PATTERN.test(node.type)) {
if (LOOP_PATTERN.test(node.type) && node.test === child) {
// This reference is inside of a loop condition.
return {
reference,
group,
isInLoop: isInLoop[node.type].bind(null, node),
modified: false
};
}
// This reference is outside of a loop condition.
break;
}
/*
* If it's inside of a group, OK if either operand is modified.
* So stores the group this reference belongs to.
*/
if (GROUP_PATTERN.test(node.type)) {
// If this expression is dynamic, no need to check.
if (hasDynamicExpressions(node)) {
break;
} else {
group = node;
}
}
child = node;
node = node.parent;
}
return null;
} | javascript | {
"resource": ""
} |
q17814 | checkReferences | train | function checkReferences(variable) {
// Gets references that exist in loop conditions.
const conditions = variable
.references
.map(toLoopCondition)
.filter(Boolean);
if (conditions.length === 0) {
return;
}
// Registers the conditions to belonging groups.
registerConditionsToGroup(conditions);
// Check the conditions are modified.
const modifiers = variable.references.filter(isWriteReference);
if (modifiers.length > 0) {
updateModifiedFlag(conditions, modifiers);
}
/*
* Reports the conditions which are not belonging to groups.
* Others will be reported after all variables are done.
*/
conditions
.filter(isUnmodifiedAndNotBelongToGroup)
.forEach(report);
} | javascript | {
"resource": ""
} |
q17815 | time | train | function time(key, fn) {
if (typeof data[key] === "undefined") {
data[key] = 0;
}
return function(...args) {
let t = process.hrtime();
fn(...args);
t = process.hrtime(t);
data[key] += t[0] * 1e3 + t[1] / 1e6;
};
} | javascript | {
"resource": ""
} |
q17816 | getConfigForNode | train | function getConfigForNode(node) {
if (
node.generator &&
context.options.length > 1 &&
context.options[1].generators
) {
return context.options[1].generators;
}
return context.options[0] || "always";
} | javascript | {
"resource": ""
} |
q17817 | isObjectOrClassMethod | train | function isObjectOrClassMethod(node) {
const parent = node.parent;
return (parent.type === "MethodDefinition" || (
parent.type === "Property" && (
parent.method ||
parent.kind === "get" ||
parent.kind === "set"
)
));
} | javascript | {
"resource": ""
} |
q17818 | hasInferredName | train | function hasInferredName(node) {
const parent = node.parent;
return isObjectOrClassMethod(node) ||
(parent.type === "VariableDeclarator" && parent.id.type === "Identifier" && parent.init === node) ||
(parent.type === "Property" && parent.value === node) ||
(parent.type === "AssignmentExpression" && parent.left.type === "Identifier" && parent.right === node) ||
(parent.type === "ExportDefaultDeclaration" && parent.declaration === node) ||
(parent.type === "AssignmentPattern" && parent.right === node);
} | javascript | {
"resource": ""
} |
q17819 | reportUnexpectedUnnamedFunction | train | function reportUnexpectedUnnamedFunction(node) {
context.report({
node,
messageId: "unnamed",
data: { name: astUtils.getFunctionNameWithKind(node) }
});
} | javascript | {
"resource": ""
} |
q17820 | generateBlogPost | train | function generateBlogPost(releaseInfo, prereleaseMajorVersion) {
const ruleList = ls("lib/rules")
// Strip the .js extension
.map(ruleFileName => ruleFileName.replace(/\.js$/u, ""))
/*
* Sort by length descending. This ensures that rule names which are substrings of other rule names are not
* matched incorrectly. For example, the string "no-undefined" should get matched with the `no-undefined` rule,
* instead of getting matched with the `no-undef` rule followed by the string "ined".
*/
.sort((ruleA, ruleB) => ruleB.length - ruleA.length);
const renderContext = Object.assign({ prereleaseMajorVersion, ruleList }, releaseInfo);
const output = ejs.render(cat("./templates/blogpost.md.ejs"), renderContext),
now = new Date(),
month = now.getMonth() + 1,
day = now.getDate(),
filename = `../eslint.github.io/_posts/${now.getFullYear()}-${
month < 10 ? `0${month}` : month}-${
day < 10 ? `0${day}` : day}-eslint-v${
releaseInfo.version}-released.md`;
output.to(filename);
} | javascript | {
"resource": ""
} |
q17821 | generateFormatterExamples | train | function generateFormatterExamples(formatterInfo, prereleaseVersion) {
const output = ejs.render(cat("./templates/formatter-examples.md.ejs"), formatterInfo);
let filename = "../eslint.github.io/docs/user-guide/formatters/index.md",
htmlFilename = "../eslint.github.io/docs/user-guide/formatters/html-formatter-example.html";
if (prereleaseVersion) {
filename = filename.replace("/docs", `/docs/${prereleaseVersion}`);
htmlFilename = htmlFilename.replace("/docs", `/docs/${prereleaseVersion}`);
if (!test("-d", path.dirname(filename))) {
mkdir(path.dirname(filename));
}
}
output.to(filename);
formatterInfo.formatterResults.html.result.to(htmlFilename);
} | javascript | {
"resource": ""
} |
q17822 | generateRuleIndexPage | train | function generateRuleIndexPage(basedir) {
const outputFile = "../eslint.github.io/_data/rules.yml",
categoryList = "conf/category-list.json",
categoriesData = JSON.parse(cat(path.resolve(categoryList)));
find(path.join(basedir, "/lib/rules/")).filter(fileType("js"))
.map(filename => [filename, path.basename(filename, ".js")])
.sort((a, b) => a[1].localeCompare(b[1]))
.forEach(pair => {
const filename = pair[0];
const basename = pair[1];
const rule = require(filename);
if (rule.meta.deprecated) {
categoriesData.deprecated.rules.push({
name: basename,
replacedBy: rule.meta.replacedBy || []
});
} else {
const output = {
name: basename,
description: rule.meta.docs.description,
recommended: rule.meta.docs.recommended || false,
fixable: !!rule.meta.fixable
},
category = lodash.find(categoriesData.categories, { name: rule.meta.docs.category });
if (!category.rules) {
category.rules = [];
}
category.rules.push(output);
}
});
const output = yaml.safeDump(categoriesData, { sortKeys: true });
output.to(outputFile);
} | javascript | {
"resource": ""
} |
q17823 | getFirstCommitOfFile | train | function getFirstCommitOfFile(filePath) {
let commits = execSilent(`git rev-list HEAD -- ${filePath}`);
commits = splitCommandResultToLines(commits);
return commits[commits.length - 1].trim();
} | javascript | {
"resource": ""
} |
q17824 | getFirstVersionOfFile | train | function getFirstVersionOfFile(filePath) {
const firstCommit = getFirstCommitOfFile(filePath);
let tags = execSilent(`git tag --contains ${firstCommit}`);
tags = splitCommandResultToLines(tags);
return tags.reduce((list, version) => {
const validatedVersion = semver.valid(version.trim());
if (validatedVersion) {
list.push(validatedVersion);
}
return list;
}, []).sort(semver.compare)[0];
} | javascript | {
"resource": ""
} |
q17825 | getFirstVersionOfDeletion | train | function getFirstVersionOfDeletion(filePath) {
const deletionCommit = getCommitDeletingFile(filePath),
tags = execSilent(`git tag --contains ${deletionCommit}`);
return splitCommandResultToLines(tags)
.map(version => semver.valid(version.trim()))
.filter(version => version)
.sort(semver.compare)[0];
} | javascript | {
"resource": ""
} |
q17826 | lintMarkdown | train | function lintMarkdown(files) {
const config = yaml.safeLoad(fs.readFileSync(path.join(__dirname, "./.markdownlint.yml"), "utf8")),
result = markdownlint.sync({
files,
config,
resultVersion: 1
}),
resultString = result.toString(),
returnCode = resultString ? 1 : 0;
if (resultString) {
console.error(resultString);
}
return { code: returnCode };
} | javascript | {
"resource": ""
} |
q17827 | getFormatterResults | train | function getFormatterResults() {
const stripAnsi = require("strip-ansi");
const formatterFiles = fs.readdirSync("./lib/formatters/"),
rules = {
"no-else-return": "warn",
indent: ["warn", 4],
"space-unary-ops": "error",
semi: ["warn", "always"],
"consistent-return": "error"
},
cli = new CLIEngine({
useEslintrc: false,
baseConfig: { extends: "eslint:recommended" },
rules
}),
codeString = [
"function addOne(i) {",
" if (i != NaN) {",
" return i ++",
" } else {",
" return",
" }",
"};"
].join("\n"),
rawMessages = cli.executeOnText(codeString, "fullOfProblems.js", true),
rulesMap = cli.getRules(),
rulesMeta = {};
Object.keys(rules).forEach(ruleId => {
rulesMeta[ruleId] = rulesMap.get(ruleId).meta;
});
return formatterFiles.reduce((data, filename) => {
const fileExt = path.extname(filename),
name = path.basename(filename, fileExt);
if (fileExt === ".js") {
const formattedOutput = cli.getFormatter(name)(
rawMessages.results,
{ rulesMeta }
);
data.formatterResults[name] = {
result: stripAnsi(formattedOutput)
};
}
return data;
}, { formatterResults: {} });
} | javascript | {
"resource": ""
} |
q17828 | hasIdInTitle | train | function hasIdInTitle(id) {
const docText = cat(docFilename);
const idOldAtEndOfTitleRegExp = new RegExp(`^# (.*?) \\(${id}\\)`, "u"); // original format
const idNewAtBeginningOfTitleRegExp = new RegExp(`^# ${id}: `, "u"); // new format is same as rules index
/*
* 1. Added support for new format.
* 2. Will remove support for old format after all docs files have new format.
* 3. Will remove this check when the main heading is automatically generated from rule metadata.
*/
return idNewAtBeginningOfTitleRegExp.test(docText) || idOldAtEndOfTitleRegExp.test(docText);
} | javascript | {
"resource": ""
} |
q17829 | isPermissible | train | function isPermissible(dependency) {
const licenses = dependency.licenses;
if (Array.isArray(licenses)) {
return licenses.some(license => isPermissible({
name: dependency.name,
licenses: license
}));
}
return OPEN_SOURCE_LICENSES.some(license => license.test(licenses));
} | javascript | {
"resource": ""
} |
q17830 | loadPerformance | train | function loadPerformance() {
echo("");
echo("Loading:");
const results = [];
for (let cnt = 0; cnt < 5; cnt++) {
const loadPerfData = loadPerf({
checkDependencies: false
});
echo(` Load performance Run #${cnt + 1}: %dms`, loadPerfData.loadTime);
results.push(loadPerfData.loadTime);
}
results.sort((a, b) => a - b);
const median = results[~~(results.length / 2)];
echo("");
echo(" Load Performance median: %dms", median);
echo("");
} | javascript | {
"resource": ""
} |
q17831 | checkSpacing | train | function checkSpacing(node) {
const tagToken = sourceCode.getTokenBefore(node.quasi);
const literalToken = sourceCode.getFirstToken(node.quasi);
const hasWhitespace = sourceCode.isSpaceBetweenTokens(tagToken, literalToken);
if (never && hasWhitespace) {
context.report({
node,
loc: tagToken.loc.start,
messageId: "unexpected",
fix(fixer) {
const comments = sourceCode.getCommentsBefore(node.quasi);
// Don't fix anything if there's a single line comment after the template tag
if (comments.some(comment => comment.type === "Line")) {
return null;
}
return fixer.replaceTextRange(
[tagToken.range[1], literalToken.range[0]],
comments.reduce((text, comment) => text + sourceCode.getText(comment), "")
);
}
});
} else if (!never && !hasWhitespace) {
context.report({
node,
loc: tagToken.loc.start,
messageId: "missing",
fix(fixer) {
return fixer.insertTextAfter(tagToken, " ");
}
});
}
} | javascript | {
"resource": ""
} |
q17832 | usesExpectedQuotes | train | function usesExpectedQuotes(node) {
return node.value.indexOf(setting.quote) !== -1 || astUtils.isSurroundedBy(node.raw, setting.quote);
} | javascript | {
"resource": ""
} |
q17833 | reportSlice | train | function reportSlice(nodes, start, end, messageId, fix) {
nodes.slice(start, end).forEach(node => {
context.report({ node, messageId, fix: fix ? getFixFunction(node) : null });
});
} | javascript | {
"resource": ""
} |
q17834 | reportAll | train | function reportAll(nodes, messageId, fix) {
reportSlice(nodes, 0, nodes.length, messageId, fix);
} | javascript | {
"resource": ""
} |
q17835 | reportAllExceptFirst | train | function reportAllExceptFirst(nodes, messageId, fix) {
reportSlice(nodes, 1, nodes.length, messageId, fix);
} | javascript | {
"resource": ""
} |
q17836 | enterFunctionInFunctionMode | train | function enterFunctionInFunctionMode(node, useStrictDirectives) {
const isInClass = classScopes.length > 0,
isParentGlobal = scopes.length === 0 && classScopes.length === 0,
isParentStrict = scopes.length > 0 && scopes[scopes.length - 1],
isStrict = useStrictDirectives.length > 0;
if (isStrict) {
if (!isSimpleParameterList(node.params)) {
context.report({ node: useStrictDirectives[0], messageId: "nonSimpleParameterList" });
} else if (isParentStrict) {
context.report({ node: useStrictDirectives[0], messageId: "unnecessary", fix: getFixFunction(useStrictDirectives[0]) });
} else if (isInClass) {
context.report({ node: useStrictDirectives[0], messageId: "unnecessaryInClasses", fix: getFixFunction(useStrictDirectives[0]) });
}
reportAllExceptFirst(useStrictDirectives, "multiple", true);
} else if (isParentGlobal) {
if (isSimpleParameterList(node.params)) {
context.report({ node, messageId: "function" });
} else {
context.report({
node,
messageId: "wrap",
data: { name: astUtils.getFunctionNameWithKind(node) }
});
}
}
scopes.push(isParentStrict || isStrict);
} | javascript | {
"resource": ""
} |
q17837 | formatMessage | train | function formatMessage(message, parentResult) {
const type = (message.fatal || message.severity === 2) ? chalk.red("error") : chalk.yellow("warning");
const msg = `${chalk.bold(message.message.replace(/([^ ])\.$/u, "$1"))}`;
const ruleId = message.fatal ? "" : chalk.dim(`(${message.ruleId})`);
const filePath = formatFilePath(parentResult.filePath, message.line, message.column);
const sourceCode = parentResult.output ? parentResult.output : parentResult.source;
const firstLine = [
`${type}:`,
`${msg}`,
ruleId ? `${ruleId}` : "",
sourceCode ? `at ${filePath}:` : `at ${filePath}`
].filter(String).join(" ");
const result = [firstLine];
if (sourceCode) {
result.push(
codeFrameColumns(sourceCode, { start: { line: message.line, column: message.column } }, { highlightCode: false })
);
}
return result.join("\n");
} | javascript | {
"resource": ""
} |
q17838 | formatSummary | train | function formatSummary(errors, warnings, fixableErrors, fixableWarnings) {
const summaryColor = errors > 0 ? "red" : "yellow";
const summary = [];
const fixablesSummary = [];
if (errors > 0) {
summary.push(`${errors} ${pluralize("error", errors)}`);
}
if (warnings > 0) {
summary.push(`${warnings} ${pluralize("warning", warnings)}`);
}
if (fixableErrors > 0) {
fixablesSummary.push(`${fixableErrors} ${pluralize("error", fixableErrors)}`);
}
if (fixableWarnings > 0) {
fixablesSummary.push(`${fixableWarnings} ${pluralize("warning", fixableWarnings)}`);
}
let output = chalk[summaryColor].bold(`${summary.join(" and ")} found.`);
if (fixableErrors || fixableWarnings) {
output += chalk[summaryColor].bold(`\n${fixablesSummary.join(" and ")} potentially fixable with the \`--fix\` option.`);
}
return output;
} | javascript | {
"resource": ""
} |
q17839 | checkVariable | train | function checkVariable(variable) {
if (variable.writeable === false && exceptions.indexOf(variable.name) === -1) {
variable.references.forEach(checkReference);
}
} | javascript | {
"resource": ""
} |
q17840 | overrideExistsForOperator | train | function overrideExistsForOperator(operator) {
return options.overrides && Object.prototype.hasOwnProperty.call(options.overrides, operator);
} | javascript | {
"resource": ""
} |
q17841 | verifyWordHasSpaces | train | function verifyWordHasSpaces(node, firstToken, secondToken, word) {
if (secondToken.range[0] === firstToken.range[1]) {
context.report({
node,
messageId: "wordOperator",
data: {
word
},
fix(fixer) {
return fixer.insertTextAfter(firstToken, " ");
}
});
}
} | javascript | {
"resource": ""
} |
q17842 | verifyWordDoesntHaveSpaces | train | function verifyWordDoesntHaveSpaces(node, firstToken, secondToken, word) {
if (astUtils.canTokensBeAdjacent(firstToken, secondToken)) {
if (secondToken.range[0] > firstToken.range[1]) {
context.report({
node,
messageId: "unexpectedAfterWord",
data: {
word
},
fix(fixer) {
return fixer.removeRange([firstToken.range[1], secondToken.range[0]]);
}
});
}
}
} | javascript | {
"resource": ""
} |
q17843 | checkUnaryWordOperatorForSpaces | train | function checkUnaryWordOperatorForSpaces(node, firstToken, secondToken, word) {
if (overrideExistsForOperator(word)) {
if (overrideEnforcesSpaces(word)) {
verifyWordHasSpaces(node, firstToken, secondToken, word);
} else {
verifyWordDoesntHaveSpaces(node, firstToken, secondToken, word);
}
} else if (options.words) {
verifyWordHasSpaces(node, firstToken, secondToken, word);
} else {
verifyWordDoesntHaveSpaces(node, firstToken, secondToken, word);
}
} | javascript | {
"resource": ""
} |
q17844 | checkForSpacesAfterYield | train | function checkForSpacesAfterYield(node) {
const tokens = sourceCode.getFirstTokens(node, 3),
word = "yield";
if (!node.argument || node.delegate) {
return;
}
checkUnaryWordOperatorForSpaces(node, tokens[0], tokens[1], word);
} | javascript | {
"resource": ""
} |
q17845 | checkForSpacesAfterAwait | train | function checkForSpacesAfterAwait(node) {
const tokens = sourceCode.getFirstTokens(node, 3);
checkUnaryWordOperatorForSpaces(node, tokens[0], tokens[1], "await");
} | javascript | {
"resource": ""
} |
q17846 | verifyNonWordsHaveSpaces | train | function verifyNonWordsHaveSpaces(node, firstToken, secondToken) {
if (node.prefix) {
if (isFirstBangInBangBangExpression(node)) {
return;
}
if (firstToken.range[1] === secondToken.range[0]) {
context.report({
node,
messageId: "operator",
data: {
operator: firstToken.value
},
fix(fixer) {
return fixer.insertTextAfter(firstToken, " ");
}
});
}
} else {
if (firstToken.range[1] === secondToken.range[0]) {
context.report({
node,
messageId: "beforeUnaryExpressions",
data: {
token: secondToken.value
},
fix(fixer) {
return fixer.insertTextBefore(secondToken, " ");
}
});
}
}
} | javascript | {
"resource": ""
} |
q17847 | verifyNonWordsDontHaveSpaces | train | function verifyNonWordsDontHaveSpaces(node, firstToken, secondToken) {
if (node.prefix) {
if (secondToken.range[0] > firstToken.range[1]) {
context.report({
node,
messageId: "unexpectedAfter",
data: {
operator: firstToken.value
},
fix(fixer) {
if (astUtils.canTokensBeAdjacent(firstToken, secondToken)) {
return fixer.removeRange([firstToken.range[1], secondToken.range[0]]);
}
return null;
}
});
}
} else {
if (secondToken.range[0] > firstToken.range[1]) {
context.report({
node,
messageId: "unexpectedBefore",
data: {
operator: secondToken.value
},
fix(fixer) {
return fixer.removeRange([firstToken.range[1], secondToken.range[0]]);
}
});
}
}
} | javascript | {
"resource": ""
} |
q17848 | checkForSpaces | train | function checkForSpaces(node) {
const tokens = node.type === "UpdateExpression" && !node.prefix
? sourceCode.getLastTokens(node, 2)
: sourceCode.getFirstTokens(node, 2);
const firstToken = tokens[0];
const secondToken = tokens[1];
if ((node.type === "NewExpression" || node.prefix) && firstToken.type === "Keyword") {
checkUnaryWordOperatorForSpaces(node, firstToken, secondToken, firstToken.value);
return;
}
const operator = node.prefix ? tokens[0].value : tokens[1].value;
if (overrideExistsForOperator(operator)) {
if (overrideEnforcesSpaces(operator)) {
verifyNonWordsHaveSpaces(node, firstToken, secondToken);
} else {
verifyNonWordsDontHaveSpaces(node, firstToken, secondToken);
}
} else if (options.nonwords) {
verifyNonWordsHaveSpaces(node, firstToken, secondToken);
} else {
verifyNonWordsDontHaveSpaces(node, firstToken, secondToken);
}
} | javascript | {
"resource": ""
} |
q17849 | removeWhitespaceError | train | function removeWhitespaceError(node) {
const locStart = node.loc.start;
const locEnd = node.loc.end;
errors = errors.filter(({ loc: errorLoc }) => {
if (errorLoc.line >= locStart.line && errorLoc.line <= locEnd.line) {
if (errorLoc.column >= locStart.column && (errorLoc.column <= locEnd.column || errorLoc.line < locEnd.line)) {
return false;
}
}
return true;
});
} | javascript | {
"resource": ""
} |
q17850 | removeInvalidNodeErrorsInTemplateLiteral | train | function removeInvalidNodeErrorsInTemplateLiteral(node) {
if (typeof node.value.raw === "string") {
if (ALL_IRREGULARS.test(node.value.raw)) {
removeWhitespaceError(node);
}
}
} | javascript | {
"resource": ""
} |
q17851 | checkForIrregularWhitespace | train | function checkForIrregularWhitespace(node) {
const sourceLines = sourceCode.lines;
sourceLines.forEach((sourceLine, lineIndex) => {
const lineNumber = lineIndex + 1;
let match;
while ((match = IRREGULAR_WHITESPACE.exec(sourceLine)) !== null) {
const location = {
line: lineNumber,
column: match.index
};
errors.push({ node, message: "Irregular whitespace not allowed.", loc: location });
}
});
} | javascript | {
"resource": ""
} |
q17852 | checkForIrregularLineTerminators | train | function checkForIrregularLineTerminators(node) {
const source = sourceCode.getText(),
sourceLines = sourceCode.lines,
linebreaks = source.match(LINE_BREAK);
let lastLineIndex = -1,
match;
while ((match = IRREGULAR_LINE_TERMINATORS.exec(source)) !== null) {
const lineIndex = linebreaks.indexOf(match[0], lastLineIndex + 1) || 0;
const location = {
line: lineIndex + 1,
column: sourceLines[lineIndex].length
};
errors.push({ node, message: "Irregular whitespace not allowed.", loc: location });
lastLineIndex = lineIndex;
}
} | javascript | {
"resource": ""
} |
q17853 | getNodeIndent | train | function getNodeIndent(node, byLastLine) {
const token = byLastLine ? sourceCode.getLastToken(node) : sourceCode.getFirstToken(node);
const srcCharsBeforeNode = sourceCode.getText(token, token.loc.start.column).split("");
const indentChars = srcCharsBeforeNode.slice(0, srcCharsBeforeNode.findIndex(char => char !== " " && char !== "\t"));
const spaces = indentChars.filter(char => char === " ").length;
const tabs = indentChars.filter(char => char === "\t").length;
return {
space: spaces,
tab: tabs,
goodChar: indentType === "space" ? spaces : tabs,
badChar: indentType === "space" ? tabs : spaces
};
} | javascript | {
"resource": ""
} |
q17854 | checkNodeIndent | train | function checkNodeIndent(node, neededIndent) {
const actualIndent = getNodeIndent(node, false);
if (
node.type !== "ArrayExpression" &&
node.type !== "ObjectExpression" &&
(actualIndent.goodChar !== neededIndent || actualIndent.badChar !== 0) &&
isNodeFirstInLine(node)
) {
report(node, neededIndent, actualIndent.space, actualIndent.tab);
}
if (node.type === "IfStatement" && node.alternate) {
const elseToken = sourceCode.getTokenBefore(node.alternate);
checkNodeIndent(elseToken, neededIndent);
if (!isNodeFirstInLine(node.alternate)) {
checkNodeIndent(node.alternate, neededIndent);
}
}
if (node.type === "TryStatement" && node.handler) {
const catchToken = sourceCode.getFirstToken(node.handler);
checkNodeIndent(catchToken, neededIndent);
}
if (node.type === "TryStatement" && node.finalizer) {
const finallyToken = sourceCode.getTokenBefore(node.finalizer);
checkNodeIndent(finallyToken, neededIndent);
}
if (node.type === "DoWhileStatement") {
const whileToken = sourceCode.getTokenAfter(node.body);
checkNodeIndent(whileToken, neededIndent);
}
} | javascript | {
"resource": ""
} |
q17855 | checkLastNodeLineIndent | train | function checkLastNodeLineIndent(node, lastLineIndent) {
const lastToken = sourceCode.getLastToken(node);
const endIndent = getNodeIndent(lastToken, true);
if ((endIndent.goodChar !== lastLineIndent || endIndent.badChar !== 0) && isNodeFirstInLine(node, true)) {
report(
node,
lastLineIndent,
endIndent.space,
endIndent.tab,
{ line: lastToken.loc.start.line, column: lastToken.loc.start.column },
true
);
}
} | javascript | {
"resource": ""
} |
q17856 | checkLastReturnStatementLineIndent | train | function checkLastReturnStatementLineIndent(node, firstLineIndent) {
/*
* in case if return statement ends with ');' we have traverse back to ')'
* otherwise we'll measure indent for ';' and replace ')'
*/
const lastToken = sourceCode.getLastToken(node, astUtils.isClosingParenToken);
const textBeforeClosingParenthesis = sourceCode.getText(lastToken, lastToken.loc.start.column).slice(0, -1);
if (textBeforeClosingParenthesis.trim()) {
// There are tokens before the closing paren, don't report this case
return;
}
const endIndent = getNodeIndent(lastToken, true);
if (endIndent.goodChar !== firstLineIndent) {
report(
node,
firstLineIndent,
endIndent.space,
endIndent.tab,
{ line: lastToken.loc.start.line, column: lastToken.loc.start.column },
true
);
}
} | javascript | {
"resource": ""
} |
q17857 | checkFirstNodeLineIndent | train | function checkFirstNodeLineIndent(node, firstLineIndent) {
const startIndent = getNodeIndent(node, false);
if ((startIndent.goodChar !== firstLineIndent || startIndent.badChar !== 0) && isNodeFirstInLine(node)) {
report(
node,
firstLineIndent,
startIndent.space,
startIndent.tab,
{ line: node.loc.start.line, column: node.loc.start.column }
);
}
} | javascript | {
"resource": ""
} |
q17858 | getParentNodeByType | train | function getParentNodeByType(node, type, stopAtList) {
let parent = node.parent;
const stopAtSet = new Set(stopAtList || ["Program"]);
while (parent.type !== type && !stopAtSet.has(parent.type) && parent.type !== "Program") {
parent = parent.parent;
}
return parent.type === type ? parent : null;
} | javascript | {
"resource": ""
} |
q17859 | isNodeInVarOnTop | train | function isNodeInVarOnTop(node, varNode) {
return varNode &&
varNode.parent.loc.start.line === node.loc.start.line &&
varNode.parent.declarations.length > 1;
} | javascript | {
"resource": ""
} |
q17860 | isArgBeforeCalleeNodeMultiline | train | function isArgBeforeCalleeNodeMultiline(node) {
const parent = node.parent;
if (parent.arguments.length >= 2 && parent.arguments[1] === node) {
return parent.arguments[0].loc.end.line > parent.arguments[0].loc.start.line;
}
return false;
} | javascript | {
"resource": ""
} |
q17861 | filterOutSameLineVars | train | function filterOutSameLineVars(node) {
return node.declarations.reduce((finalCollection, elem) => {
const lastElem = finalCollection[finalCollection.length - 1];
if ((elem.loc.start.line !== node.loc.start.line && !lastElem) ||
(lastElem && lastElem.loc.start.line !== elem.loc.start.line)) {
finalCollection.push(elem);
}
return finalCollection;
}, []);
} | javascript | {
"resource": ""
} |
q17862 | getTopConcatBinaryExpression | train | function getTopConcatBinaryExpression(node) {
let currentNode = node;
while (isConcatenation(currentNode.parent)) {
currentNode = currentNode.parent;
}
return currentNode;
} | javascript | {
"resource": ""
} |
q17863 | isOctalEscapeSequence | train | function isOctalEscapeSequence(node) {
// No need to check TemplateLiterals – would throw error with octal escape
const isStringLiteral = node.type === "Literal" && typeof node.value === "string";
if (!isStringLiteral) {
return false;
}
const match = node.raw.match(/^([^\\]|\\[^0-7])*\\([0-7]{1,3})/u);
if (match) {
// \0 is actually not considered an octal
if (match[2] !== "0" || typeof match[3] !== "undefined") {
return true;
}
}
return false;
} | javascript | {
"resource": ""
} |
q17864 | hasOctalEscapeSequence | train | function hasOctalEscapeSequence(node) {
if (isConcatenation(node)) {
return hasOctalEscapeSequence(node.left) || hasOctalEscapeSequence(node.right);
}
return isOctalEscapeSequence(node);
} | javascript | {
"resource": ""
} |
q17865 | hasStringLiteral | train | function hasStringLiteral(node) {
if (isConcatenation(node)) {
// `left` is deeper than `right` normally.
return hasStringLiteral(node.right) || hasStringLiteral(node.left);
}
return astUtils.isStringLiteral(node);
} | javascript | {
"resource": ""
} |
q17866 | hasNonStringLiteral | train | function hasNonStringLiteral(node) {
if (isConcatenation(node)) {
// `left` is deeper than `right` normally.
return hasNonStringLiteral(node.right) || hasNonStringLiteral(node.left);
}
return !astUtils.isStringLiteral(node);
} | javascript | {
"resource": ""
} |
q17867 | getTextBetween | train | function getTextBetween(node1, node2) {
const allTokens = [node1].concat(sourceCode.getTokensBetween(node1, node2)).concat(node2);
const sourceText = sourceCode.getText();
return allTokens.slice(0, -1).reduce((accumulator, token, index) => accumulator + sourceText.slice(token.range[1], allTokens[index + 1].range[0]), "");
} | javascript | {
"resource": ""
} |
q17868 | getTemplateLiteral | train | function getTemplateLiteral(currentNode, textBeforeNode, textAfterNode) {
if (currentNode.type === "Literal" && typeof currentNode.value === "string") {
/*
* If the current node is a string literal, escape any instances of ${ or ` to prevent them from being interpreted
* as a template placeholder. However, if the code already contains a backslash before the ${ or `
* for some reason, don't add another backslash, because that would change the meaning of the code (it would cause
* an actual backslash character to appear before the dollar sign).
*/
return `\`${currentNode.raw.slice(1, -1).replace(/\\*(\$\{|`)/gu, matched => {
if (matched.lastIndexOf("\\") % 2) {
return `\\${matched}`;
}
return matched;
// Unescape any quotes that appear in the original Literal that no longer need to be escaped.
}).replace(new RegExp(`\\\\${currentNode.raw[0]}`, "gu"), currentNode.raw[0])}\``;
}
if (currentNode.type === "TemplateLiteral") {
return sourceCode.getText(currentNode);
}
if (isConcatenation(currentNode) && hasStringLiteral(currentNode) && hasNonStringLiteral(currentNode)) {
const plusSign = sourceCode.getFirstTokenBetween(currentNode.left, currentNode.right, token => token.value === "+");
const textBeforePlus = getTextBetween(currentNode.left, plusSign);
const textAfterPlus = getTextBetween(plusSign, currentNode.right);
const leftEndsWithCurly = endsWithTemplateCurly(currentNode.left);
const rightStartsWithCurly = startsWithTemplateCurly(currentNode.right);
if (leftEndsWithCurly) {
// If the left side of the expression ends with a template curly, add the extra text to the end of the curly bracket.
// `foo${bar}` /* comment */ + 'baz' --> `foo${bar /* comment */ }${baz}`
return getTemplateLiteral(currentNode.left, textBeforeNode, textBeforePlus + textAfterPlus).slice(0, -1) +
getTemplateLiteral(currentNode.right, null, textAfterNode).slice(1);
}
if (rightStartsWithCurly) {
// Otherwise, if the right side of the expression starts with a template curly, add the text there.
// 'foo' /* comment */ + `${bar}baz` --> `foo${ /* comment */ bar}baz`
return getTemplateLiteral(currentNode.left, textBeforeNode, null).slice(0, -1) +
getTemplateLiteral(currentNode.right, textBeforePlus + textAfterPlus, textAfterNode).slice(1);
}
/*
* Otherwise, these nodes should not be combined into a template curly, since there is nowhere to put
* the text between them.
*/
return `${getTemplateLiteral(currentNode.left, textBeforeNode, null)}${textBeforePlus}+${textAfterPlus}${getTemplateLiteral(currentNode.right, textAfterNode, null)}`;
}
return `\`\${${textBeforeNode || ""}${sourceCode.getText(currentNode)}${textAfterNode || ""}}\``;
} | javascript | {
"resource": ""
} |
q17869 | fixNonStringBinaryExpression | train | function fixNonStringBinaryExpression(fixer, node) {
const topBinaryExpr = getTopConcatBinaryExpression(node.parent);
if (hasOctalEscapeSequence(topBinaryExpr)) {
return null;
}
return fixer.replaceText(topBinaryExpr, getTemplateLiteral(topBinaryExpr, null, null));
} | javascript | {
"resource": ""
} |
q17870 | checkForStringConcat | train | function checkForStringConcat(node) {
if (!astUtils.isStringLiteral(node) || !isConcatenation(node.parent)) {
return;
}
const topBinaryExpr = getTopConcatBinaryExpression(node.parent);
// Checks whether or not this node had been checked already.
if (done[topBinaryExpr.range[0]]) {
return;
}
done[topBinaryExpr.range[0]] = true;
if (hasNonStringLiteral(topBinaryExpr)) {
context.report({
node: topBinaryExpr,
message: "Unexpected string concatenation.",
fix: fixer => fixNonStringBinaryExpression(fixer, node)
});
}
} | javascript | {
"resource": ""
} |
q17871 | reportUnnecessaryAwait | train | function reportUnnecessaryAwait(node) {
context.report({
node: context.getSourceCode().getFirstToken(node),
loc: node.loc,
message
});
} | javascript | {
"resource": ""
} |
q17872 | hasSameTokens | train | function hasSameTokens(nodeA, nodeB) {
const tokensA = sourceCode.getTokens(nodeA);
const tokensB = sourceCode.getTokens(nodeB);
return tokensA.length === tokensB.length &&
tokensA.every((token, index) => token.type === tokensB[index].type && token.value === tokensB[index].value);
} | javascript | {
"resource": ""
} |
q17873 | isConstant | train | function isConstant(node, inBooleanPosition) {
switch (node.type) {
case "Literal":
case "ArrowFunctionExpression":
case "FunctionExpression":
case "ObjectExpression":
case "ArrayExpression":
return true;
case "UnaryExpression":
if (node.operator === "void") {
return true;
}
return (node.operator === "typeof" && inBooleanPosition) ||
isConstant(node.argument, true);
case "BinaryExpression":
return isConstant(node.left, false) &&
isConstant(node.right, false) &&
node.operator !== "in";
case "LogicalExpression": {
const isLeftConstant = isConstant(node.left, inBooleanPosition);
const isRightConstant = isConstant(node.right, inBooleanPosition);
const isLeftShortCircuit = (isLeftConstant && isLogicalIdentity(node.left, node.operator));
const isRightShortCircuit = (isRightConstant && isLogicalIdentity(node.right, node.operator));
return (isLeftConstant && isRightConstant) ||
(
// in the case of an "OR", we need to know if the right constant value is truthy
node.operator === "||" &&
isRightConstant &&
node.right.value &&
(
!node.parent ||
node.parent.type !== "BinaryExpression" ||
!(EQUALITY_OPERATORS.includes(node.parent.operator) || RELATIONAL_OPERATORS.includes(node.parent.operator))
)
) ||
isLeftShortCircuit ||
isRightShortCircuit;
}
case "AssignmentExpression":
return (node.operator === "=") && isConstant(node.right, inBooleanPosition);
case "SequenceExpression":
return isConstant(node.expressions[node.expressions.length - 1], inBooleanPosition);
// no default
}
return false;
} | javascript | {
"resource": ""
} |
q17874 | trackConstantConditionLoop | train | function trackConstantConditionLoop(node) {
if (node.test && isConstant(node.test, true)) {
loopsInCurrentScope.add(node);
}
} | javascript | {
"resource": ""
} |
q17875 | checkConstantConditionLoopInSet | train | function checkConstantConditionLoopInSet(node) {
if (loopsInCurrentScope.has(node)) {
loopsInCurrentScope.delete(node);
context.report({ node: node.test, messageId: "unexpected" });
}
} | javascript | {
"resource": ""
} |
q17876 | reportIfConstant | train | function reportIfConstant(node) {
if (node.test && isConstant(node.test, true)) {
context.report({ node: node.test, messageId: "unexpected" });
}
} | javascript | {
"resource": ""
} |
q17877 | optionToDefinition | train | function optionToDefinition(option, defaults) {
if (!option) {
return defaults;
}
return typeof option === "string"
? optionDefinitions[option]
: Object.assign({}, defaults, option);
} | javascript | {
"resource": ""
} |
q17878 | getStarToken | train | function getStarToken(node) {
return sourceCode.getFirstToken(
(node.parent.method || node.parent.type === "MethodDefinition") ? node.parent : node,
isStarToken
);
} | javascript | {
"resource": ""
} |
q17879 | checkFunction | train | function checkFunction(node) {
if (!node.generator) {
return;
}
const starToken = getStarToken(node);
const prevToken = sourceCode.getTokenBefore(starToken);
const nextToken = sourceCode.getTokenAfter(starToken);
let kind = "named";
if (node.parent.type === "MethodDefinition" || (node.parent.type === "Property" && node.parent.method)) {
kind = "method";
} else if (!node.id) {
kind = "anonymous";
}
// Only check before when preceded by `function`|`static` keyword
if (!(kind === "method" && starToken === sourceCode.getFirstToken(node.parent))) {
checkSpacing(kind, "before", prevToken, starToken);
}
checkSpacing(kind, "after", starToken, nextToken);
} | javascript | {
"resource": ""
} |
q17880 | getColonToken | train | function getColonToken(node) {
if (node.test) {
return sourceCode.getTokenAfter(node.test, astUtils.isColonToken);
}
return sourceCode.getFirstToken(node, 1);
} | javascript | {
"resource": ""
} |
q17881 | isValidSpacing | train | function isValidSpacing(left, right, expected) {
return (
astUtils.isClosingBraceToken(right) ||
!astUtils.isTokenOnSameLine(left, right) ||
sourceCode.isSpaceBetweenTokens(left, right) === expected
);
} | javascript | {
"resource": ""
} |
q17882 | commentsExistBetween | train | function commentsExistBetween(left, right) {
return sourceCode.getFirstTokenBetween(
left,
right,
{
includeComments: true,
filter: astUtils.isCommentToken
}
) !== null;
} | javascript | {
"resource": ""
} |
q17883 | fix | train | function fix(fixer, left, right, spacing) {
if (commentsExistBetween(left, right)) {
return null;
}
if (spacing) {
return fixer.insertTextAfter(left, " ");
}
return fixer.removeRange([left.range[1], right.range[0]]);
} | javascript | {
"resource": ""
} |
q17884 | containsOnlyIdentifiers | train | function containsOnlyIdentifiers(node) {
if (node.type === "Identifier") {
return true;
}
if (node.type === "MemberExpression") {
if (node.object.type === "Identifier") {
return true;
}
if (node.object.type === "MemberExpression") {
return containsOnlyIdentifiers(node.object);
}
}
return false;
} | javascript | {
"resource": ""
} |
q17885 | isCallback | train | function isCallback(node) {
return containsOnlyIdentifiers(node.callee) && callbacks.indexOf(sourceCode.getText(node.callee)) > -1;
} | javascript | {
"resource": ""
} |
q17886 | isCallbackExpression | train | function isCallbackExpression(node, parentNode) {
// ensure the parent node exists and is an expression
if (!parentNode || parentNode.type !== "ExpressionStatement") {
return false;
}
// cb()
if (parentNode.expression === node) {
return true;
}
// special case for cb && cb() and similar
if (parentNode.expression.type === "BinaryExpression" || parentNode.expression.type === "LogicalExpression") {
if (parentNode.expression.right === node) {
return true;
}
}
return false;
} | javascript | {
"resource": ""
} |
q17887 | enterFunction | train | function enterFunction(node) {
// `this` can be invalid only under strict mode.
stack.push({
init: !context.getScope().isStrict,
node,
valid: true
});
} | javascript | {
"resource": ""
} |
q17888 | areLineBreaksRequired | train | function areLineBreaksRequired(node, options, first, last) {
let objectProperties;
if (node.type === "ObjectExpression" || node.type === "ObjectPattern") {
objectProperties = node.properties;
} else {
// is ImportDeclaration or ExportNamedDeclaration
objectProperties = node.specifiers
.filter(s => s.type === "ImportSpecifier" || s.type === "ExportSpecifier");
}
return objectProperties.length >= options.minProperties ||
(
options.multiline &&
objectProperties.length > 0 &&
first.loc.start.line !== last.loc.end.line
);
} | javascript | {
"resource": ""
} |
q17889 | calculateStatsPerFile | train | function calculateStatsPerFile(messages) {
return messages.reduce((stat, message) => {
if (message.fatal || message.severity === 2) {
stat.errorCount++;
if (message.fix) {
stat.fixableErrorCount++;
}
} else {
stat.warningCount++;
if (message.fix) {
stat.fixableWarningCount++;
}
}
return stat;
}, {
errorCount: 0,
warningCount: 0,
fixableErrorCount: 0,
fixableWarningCount: 0
});
} | javascript | {
"resource": ""
} |
q17890 | calculateStatsPerRun | train | function calculateStatsPerRun(results) {
return results.reduce((stat, result) => {
stat.errorCount += result.errorCount;
stat.warningCount += result.warningCount;
stat.fixableErrorCount += result.fixableErrorCount;
stat.fixableWarningCount += result.fixableWarningCount;
return stat;
}, {
errorCount: 0,
warningCount: 0,
fixableErrorCount: 0,
fixableWarningCount: 0
});
} | javascript | {
"resource": ""
} |
q17891 | processFile | train | function processFile(filename, configHelper, options, linter) {
const text = fs.readFileSync(path.resolve(filename), "utf8");
return processText(
text,
configHelper,
filename,
options.fix,
options.allowInlineConfig,
options.reportUnusedDisableDirectives,
linter
);
} | javascript | {
"resource": ""
} |
q17892 | isIIFE | train | function isIIFE(node) {
return node.type === "FunctionExpression" && node.parent && node.parent.type === "CallExpression" && node.parent.callee === node;
} | javascript | {
"resource": ""
} |
q17893 | isEmbedded | train | function isEmbedded(node) {
if (!node.parent) {
return false;
}
if (node !== node.parent.value) {
return false;
}
if (node.parent.type === "MethodDefinition") {
return true;
}
if (node.parent.type === "Property") {
return node.parent.method === true || node.parent.kind === "get" || node.parent.kind === "set";
}
return false;
} | javascript | {
"resource": ""
} |
q17894 | processFunction | train | function processFunction(funcNode) {
const node = isEmbedded(funcNode) ? funcNode.parent : funcNode;
if (!IIFEs && isIIFE(node)) {
return;
}
let lineCount = 0;
for (let i = node.loc.start.line - 1; i < node.loc.end.line; ++i) {
const line = lines[i];
if (skipComments) {
if (commentLineNumbers.has(i + 1) && isFullLineComment(line, i + 1, commentLineNumbers.get(i + 1))) {
continue;
}
}
if (skipBlankLines) {
if (line.match(/^\s*$/u)) {
continue;
}
}
lineCount++;
}
if (lineCount > maxLines) {
const name = astUtils.getFunctionNameWithKind(funcNode);
context.report({
node,
messageId: "exceed",
data: { name, lineCount, maxLines }
});
}
} | javascript | {
"resource": ""
} |
q17895 | isValidIdentifierPair | train | function isValidIdentifierPair(ctorParam, superArg) {
return (
ctorParam.type === "Identifier" &&
superArg.type === "Identifier" &&
ctorParam.name === superArg.name
);
} | javascript | {
"resource": ""
} |
q17896 | isRedundantSuperCall | train | function isRedundantSuperCall(body, ctorParams) {
return (
isSingleSuperCall(body) &&
ctorParams.every(isSimple) &&
(
isSpreadArguments(body[0].expression.arguments) ||
isPassingThrough(ctorParams, body[0].expression.arguments)
)
);
} | javascript | {
"resource": ""
} |
q17897 | checkForConstructor | train | function checkForConstructor(node) {
if (node.kind !== "constructor") {
return;
}
const body = node.value.body.body;
const ctorParams = node.value.params;
const superClass = node.parent.parent.superClass;
if (superClass ? isRedundantSuperCall(body, ctorParams) : (body.length === 0)) {
context.report({
node,
message: "Useless constructor."
});
}
} | javascript | {
"resource": ""
} |
q17898 | beforeLoc | train | function beforeLoc(loc, line, column) {
if (line < loc.start.line) {
return true;
}
return line === loc.start.line && column < loc.start.column;
} | javascript | {
"resource": ""
} |
q17899 | afterLoc | train | function afterLoc(loc, line, column) {
if (line > loc.end.line) {
return true;
}
return line === loc.end.line && column > loc.end.column;
} | javascript | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.