UNPKG

eslint-plugin-unicorn

Version:
74 lines (64 loc) • 1.63 kB
import {isMethodCall} from './ast/index.js'; import { getCallExpressionTokens, getStaticNumberValue, hasNonDirectiveComment, shouldSkipKnownNonArrayReceiver, } from './utils/index.js'; const MESSAGE_ID = 'no-magic-array-flat-depth'; const messages = { [MESSAGE_ID]: 'Magic number as depth is not allowed.', }; /** @param {import('eslint').Rule.RuleContext} context */ const create = context => { context.on('CallExpression', callExpression => { if (!isMethodCall(callExpression, { method: 'flat', argumentsLength: 1, optionalCall: false, })) { return; } const [depth] = callExpression.arguments; // `getStaticNumberValue()` also unwraps a `-2`/`+2` unary expression and TypeScript wrappers const depthValue = getStaticNumberValue(depth); if (typeof depthValue !== 'number' || depthValue === 1) { return; } const {sourceCode} = context; const { openingParenthesisToken, closingParenthesisToken, } = getCallExpressionTokens(callExpression, context); if ( hasNonDirectiveComment(context, [sourceCode.getRange(openingParenthesisToken)[1], sourceCode.getRange(closingParenthesisToken)[0]]) || shouldSkipKnownNonArrayReceiver(callExpression.callee.object, context) ) { return; } return { node: depth, messageId: MESSAGE_ID, }; }); }; /** @type {import('eslint').Rule.RuleModule} */ const config = { create, meta: { type: 'suggestion', docs: { description: 'Disallow a magic number as the `depth` argument in `Array#flat(…).`', recommended: 'unopinionated', }, messages, languages: [ 'js/js', ], }, }; export default config;