eslint-plugin-lodash
Version:
Lodash specific linting rules for ESLint
50 lines (39 loc) • 2 kB
JavaScript
/**
* @fileoverview Rule to check if a call to _.forEach should be a call to _.filter
*/
;
/**
* @fileoverview Rule to check if a call to _.forEach should be a call to _.filter
*/
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
module.exports = {
create: function create(context) {
var _require = require('../util/lodashUtil');
var getLodashMethodVisitors = _require.getLodashMethodVisitors;
var _require2 = require('../util/astUtil');
var getFirstFunctionLine = _require2.getFirstFunctionLine;
var hasOnlyOneStatement = _require2.hasOnlyOneStatement;
var getMethodName = _require2.getMethodName;
var isFunctionDefinitionWithBlock = _require2.isFunctionDefinitionWithBlock;
var collectParameterValues = _require2.collectParameterValues;
var _require3 = require('../util/methodDataUtil');
var isAliasOfMethod = _require3.isAliasOfMethod;
var get = require('lodash/get');
var includes = require('lodash/includes');
function onlyHasPush(func) {
var firstLine = getFirstFunctionLine(func);
var firstParam = get(func, 'params[0]');
var exp = func && !isFunctionDefinitionWithBlock(func) ? firstLine : firstLine && firstLine.expression;
return func && hasOnlyOneStatement(func) && getMethodName(exp) === 'push' && !includes(collectParameterValues(firstParam), get(exp, 'callee.object.name'));
}
return getLodashMethodVisitors(context, function (node, iteratee, _ref) {
var method = _ref.method;
var version = _ref.version;
if (isAliasOfMethod(version, 'forEach', method) && onlyHasPush(iteratee)) {
context.report(node, 'Prefer _.map over a _.forEach with a push to an array inside');
}
});
}
};