eslint-plugin-lodash
Version:
Lodash specific linting rules for ESLint
54 lines (41 loc) • 2.25 kB
JavaScript
/**
* @fileoverview Rule to check if a call to filter should be a call to compact
*/
;
/**
* @fileoverview Rule to check if a call to filter should be a call to compact
*/
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
module.exports = {
create: function create(context) {
var _require = require('../util/lodashUtil');
var getLodashMethodVisitors = _require.getLodashMethodVisitors;
var _require2 = require('../util/astUtil');
var isNegationExpression = _require2.isNegationExpression;
var isIdentifierWithName = _require2.isIdentifierWithName;
var getValueReturnedInFirstStatement = _require2.getValueReturnedInFirstStatement;
var getFirstParamName = _require2.getFirstParamName;
var _require3 = require('../util/methodDataUtil');
var isAliasOfMethod = _require3.isAliasOfMethod;
function isDoubleNegationOfParam(exp, paramName) {
return isNegationExpression(exp) && isNegationExpression(exp.argument) && isIdentifierWithName(exp.argument.argument, paramName);
}
function isCallToBooleanCastOfParam(exp, paramName) {
return exp && exp.type === 'CallExpression' && exp.callee.name === 'Boolean' && isIdentifierWithName(exp.arguments[0], paramName);
}
function isBooleanCastingFunction(func) {
var returnValue = getValueReturnedInFirstStatement(func);
var paramName = getFirstParamName(func);
return func && func.type === 'Identifier' && func.name === 'Boolean' || isIdentifierWithName(returnValue, paramName) || isDoubleNegationOfParam(returnValue, paramName) || isCallToBooleanCastOfParam(returnValue, paramName);
}
return getLodashMethodVisitors(context, function (node, iteratee, _ref) {
var method = _ref.method;
var version = _ref.version;
if (isAliasOfMethod(version, 'filter', method) && isBooleanCastingFunction(iteratee)) {
context.report(node, 'Prefer _.compact over filtering of Boolean casting');
}
});
}
};