Skip to content

Commit

Permalink
fix(eslint-plugin): [no-magic-numbers] fix implementation of the `ign…
Browse files Browse the repository at this point in the history
…ore` option (#9167)

* fix(eslint-plugin): [no-magic-numbers] fix implementation of the `ignore` option

* Passed node's value as parameter

* Simple tests to check if value was correctly not ignored

* Simple tests to check if value was correctly ignored
  • Loading branch information
Vinccool96 committed Jun 6, 2024
1 parent 0db10a9 commit bf5394d
Show file tree
Hide file tree
Showing 3 changed files with 388 additions and 2 deletions.
45 changes: 44 additions & 1 deletion packages/eslint-plugin/src/rules/no-magic-numbers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,11 +58,14 @@ export default createRule<Options, MessageIds>({
ignoreNumericLiteralTypes: false,
ignoreEnums: false,
ignoreReadonlyClassProperties: false,
ignoreTypeIndexes: false,
},
],
create(context, [options]) {
const rules = baseRule.create(context);

const ignored = new Set((options.ignore ?? []).map(normalizeIgnoreValue));

return {
Literal(node): void {
// If it’s not a numeric literal we’re not interested
Expand All @@ -76,8 +79,12 @@ export default createRule<Options, MessageIds>({
// not one of our exception cases, and we’ll fall back to the base rule.
let isAllowed: boolean | undefined;

// Check if the node is ignored
if (ignored.has(normalizeLiteralValue(node, node.value))) {
isAllowed = true;
}
// Check if the node is a TypeScript enum declaration
if (isParentTSEnumDeclaration(node)) {
else if (isParentTSEnumDeclaration(node)) {
isAllowed = options.ignoreEnums === true;
}
// Check TypeScript specific nodes for Numeric Literal
Expand Down Expand Up @@ -129,6 +136,42 @@ export default createRule<Options, MessageIds>({
},
});

/**
* Convert the value to bigint if it's a string. Otherwise, return the value as-is.
* @param value The value to normalize.
* @returns The normalized value.
*/
function normalizeIgnoreValue(
value: bigint | number | string,
): bigint | number {
if (typeof value === 'string') {
return BigInt(value.slice(0, -1));
}

return value;
}

/**
* Converts the node to its numeric value, handling prefixed numbers (-1 / +1)
* @param node the node to normalize.
* @param value the node's value.
*/
function normalizeLiteralValue(
node: TSESTree.BigIntLiteral | TSESTree.NumberLiteral,
value: number | bigint,
): bigint | number {
if (
node.parent.type === AST_NODE_TYPES.UnaryExpression &&
['-', '+'].includes(node.parent.operator)
) {
if (node.parent.operator === '-') {
return -value;
}
}

return value;
}

/**
* Gets the true parent of the literal, handling prefixed numbers (-1 / +1)
*/
Expand Down

0 comments on commit bf5394d

Please sign in to comment.