UNPKG

eslint-plugin-lodash

Version:

Lodash specific linting rules for ESLint

70 lines (61 loc) 2.55 kB
/** * @fileoverview Rule to check if the expression could be better expressed as a _.constant */ 'use strict'; /** * @fileoverview Rule to check if the expression could be better expressed as a _.constant */ //------------------------------------------------------------------------------ // Rule Definition //------------------------------------------------------------------------------ module.exports = { meta: { schema: [{ type: 'boolean' }, { type: 'boolean' }] }, create: function create(context) { var _require = require('../util/astUtil'); var getValueReturnedInFirstStatement = _require.getValueReturnedInFirstStatement; var shouldCheckArrowFunctions = context.options[0] !== undefined ? context.options[0] : true; var shouldCheckFunctionDeclarations = context.options[1] !== undefined ? context.options[1] : false; function isCompletelyLiteral(node) { switch (node.type) { case 'Literal': return true; case 'BinaryExpression': return isCompletelyLiteral(node.left) && isCompletelyLiteral(node.right); case 'UnaryExpression': return isCompletelyLiteral(node.argument); case 'ConditionalExpression': return isCompletelyLiteral(node.test) && isCompletelyLiteral(node.consequent) && isCompletelyLiteral(node.alternate); default: return false; } } function reportIfLikeConstant(func, node) { var valueReturnedInFirstLine = func(node); if (valueReturnedInFirstLine && isCompletelyLiteral(valueReturnedInFirstLine)) { context.report(node, 'Prefer _.constant over a function returning a literal'); } } function handleFunctionDefinition(node) { reportIfLikeConstant(getValueReturnedInFirstStatement, node); } return { FunctionExpression: handleFunctionDefinition, FunctionDeclaration: function FunctionDeclaration(node) { if (shouldCheckFunctionDeclarations) { handleFunctionDefinition(node); } }, ArrowFunctionExpression: function ArrowFunctionExpression(node) { if (shouldCheckArrowFunctions) { handleFunctionDefinition(node); } } }; } };