function-name

Try in Playground
javascript-inclusiveBest PracticeWarning

0

inclusivity

No CWE or CVE

Make sure that a function does not contain non-inclusive words.

Ast Rule: function definition


function-name

How to write a rule
const NAMES_TO_REPLACE = new Map([
  ['blacklist', 'denylist'],
  ['whitelist', 'allowlist'],
  ['master', 'primary'],
  ['slave', 'secondary'],
  ['dummy', 'placeholder'],
]);

const checkString = (node, avoidString, replaceString) => {
  if (node && node.value && node.value.toLowerCase().includes(avoidString)) {
		const originalName = node.value;
		const startIndex = node.value.toLowerCase().indexOf(avoidString);
		
		const isUpperCase = node.value.charAt(startIndex) == node.value.charAt(startIndex).toUpperCase();
		
		if (isUpperCase) {
			replaceString = replaceString[0].toUpperCase() + replaceString.substring(1); 
		}
		const endIndex = startIndex + avoidString.length;
		
    const updatedName = originalName.substring(0, startIndex) + replaceString + originalName.substring(endIndex, originalName.length);
    const error = buildError(node.start.line, node.start.col,
      node.end.line, node.end.col,
      `do not use word ${avoidString}`, "INFO", "BEST_PRACTICES");
    const edit = buildEditUpdate(node.start.line, node.start.col,
      node.end.line, node.end.col,
      updatedName);
    const fix = buildFix(`use ${updatedName} instead`, [edit]);
    addError(error.addFix(fix));
  }
}

function visit(node, filename, code) {

  // If filename starts or ends with test_ or _test, do not do anything
  if (filename.includes("_test.py") || filename.startsWith("test_")) {
    return;
  }
  for (const name of NAMES_TO_REPLACE.keys()) {
    const replacement = NAMES_TO_REPLACE.get(name);
    if (node.name && node.name.value) {
      checkString(node.name, name, replacement);
    }

    // if the parameters of the function are defined
    if (node.parameters && node.parameters.values) {

      node.parameters.values.forEach(parameter => {
        checkString(parameter.name, name, replacement);
      });
    }
  }
}

my-function2.js

Expected test result: has error

function functionBlacklist(argument) {
	console.log("foo")
}

my-function.js

Expected test result: has error

function blacklistFunction(argument) {
	console.log("foo")
}
Add comment

Log in to add a comment


    Be the first one to leave a comment!

Codiga Logo
Codiga Hub
  • Rulesets
  • Playground
  • Snippets
  • Cookbooks
soc-2 icon

We are SOC-2 Compliance Certified

G2 high performer medal

Codiga – All rights reserved 2022.