2 * @fileoverview Rule that warns when identifier names are shorter or longer
3 * than the values provided in configuration.
4 * @author Burak Yigit Kaya aka BYK
9 //------------------------------------------------------------------------------
11 //------------------------------------------------------------------------------
18 description: "enforce minimum and maximum identifier lengths",
19 category: "Stylistic Issues",
21 url: "https://eslint.org/docs/rules/id-length"
43 enum: ["always", "never"]
46 additionalProperties: false
50 tooShort: "Identifier name '{{name}}' is too short (< {{min}}).",
51 tooLong: "Identifier name '{{name}}' is too long (> {{max}})."
56 const options = context.options[0] || {};
57 const minLength = typeof options.min !== "undefined" ? options.min : 2;
58 const maxLength = typeof options.max !== "undefined" ? options.max : Infinity;
59 const properties = options.properties !== "never";
60 const exceptions = (options.exceptions ? options.exceptions : [])
61 .reduce((obj, item) => {
67 const SUPPORTED_EXPRESSIONS = {
68 MemberExpression: properties && function(parent) {
69 return !parent.computed && (
71 // regular property assignment
72 (parent.parent.left === parent && parent.parent.type === "AssignmentExpression" ||
74 // or the last identifier in an ObjectPattern destructuring
75 parent.parent.type === "Property" && parent.parent.value === parent &&
76 parent.parent.parent.type === "ObjectPattern" && parent.parent.parent.parent.left === parent.parent.parent)
79 AssignmentPattern(parent, node) {
80 return parent.left === node;
82 VariableDeclarator(parent, node) {
83 return parent.id === node;
85 Property: properties && function(parent, node) {
86 return parent.key === node;
88 ImportDefaultSpecifier: true,
90 FunctionExpression: true,
91 ArrowFunctionExpression: true,
92 ClassDeclaration: true,
93 FunctionDeclaration: true,
94 MethodDefinition: true,
100 const name = node.name;
101 const parent = node.parent;
103 const isShort = name.length < minLength;
104 const isLong = name.length > maxLength;
106 if (!(isShort || isLong) || exceptions[name]) {
107 return; // Nothing to report
110 const isValidExpression = SUPPORTED_EXPRESSIONS[parent.type];
112 if (isValidExpression && (isValidExpression === true || isValidExpression(parent, node))) {
115 messageId: isShort ? "tooShort" : "tooLong",
116 data: { name, min: minLength, max: maxLength }