Skip to content

Commit

Permalink
feat(helpers): getEnumPropertyName helper
Browse files Browse the repository at this point in the history
  • Loading branch information
adamviktora committed Oct 30, 2024
1 parent a84ba10 commit c43d8a6
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { Rule } from "eslint";
import { Identifier, MemberExpression } from "estree-jsx";
import { getVariableDeclaration } from ".";

/** Used to get a property name on an enum (MemberExpression). */
export function getEnumPropertyName(
context: Rule.RuleContext,
enumNode: MemberExpression
) {
const isIdentifier = enumNode.property.type === "Identifier";
const computed = enumNode.computed;

// E.g. const key = "key"; someEnum[key]
if (isIdentifier && computed) {
const scope = context.getSourceCode().getScope(enumNode);
const propertyName = (enumNode.property as Identifier).name;
const propertyVariable = getVariableDeclaration(propertyName, scope);
return propertyVariable?.defs[0].node.init.value as string;
}
// E.g. someEnum.key
if (isIdentifier && !computed) {
return (enumNode.property as Identifier).name;
}
// E.g. someEnum["key"]
if (enumNode.property.type === "Literal") {
return enumNode.property.value as string;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ export * from "./getChildJSXElementByName";
export * from "./getCodeModDataTag";
export * from "./getComponentImportName";
export * from "./getEndRange";
export * from "./getEnumPropertyName";
export * from "./getFromPackage";
export * from "./getImportedName";
export * from "./getImportPath";
Expand Down

0 comments on commit c43d8a6

Please sign in to comment.