-
Notifications
You must be signed in to change notification settings - Fork 19
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(helpers): getEnumPropertyName helper
- Loading branch information
1 parent
a84ba10
commit c43d8a6
Showing
2 changed files
with
29 additions
and
0 deletions.
There are no files selected for viewing
28 changes: 28 additions & 0 deletions
28
packages/eslint-plugin-pf-codemods/src/rules/helpers/getEnumPropertyName.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters