Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading