Skip to content

Commit 5fccafc

Browse files
committed

File tree

1 file changed

+26
-1
lines changed

1 file changed

+26
-1
lines changed

crates/oxc_linter/src/rules/unicorn/prefer_array_flat_map.rs

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
use oxc_ast::{
22
AstKind,
3-
ast::{Argument, Expression},
3+
ast::{Argument, CallExpression, Expression},
44
};
55
use oxc_diagnostics::OxcDiagnostic;
66
use oxc_macros::declare_oxc_lint;
@@ -43,6 +43,9 @@ declare_oxc_lint!(
4343
fix
4444
);
4545

46+
// skip React.Children because we are only looking at `StaticMemberExpression.property` and not its object
47+
const IGNORE_OBJECTS: [&str; 1] = [/* "React.Children", */ "Children"];
48+
4649
impl Rule for PreferArrayFlatMap {
4750
fn run<'a>(&self, node: &AstNode<'a>, ctx: &LintContext<'a>) {
4851
let AstKind::CallExpression(flat_call_expr) = node.kind() else {
@@ -67,6 +70,11 @@ impl Rule for PreferArrayFlatMap {
6770
return;
6871
}
6972

73+
// Check for Call Expressions which should be ignored
74+
if is_ignored_call_expression(call_expr) {
75+
return;
76+
}
77+
7078
if let Some(first_arg) = flat_call_expr.arguments.first() {
7179
// `Array.prototype.flat` rounds down the argument.
7280
// So `.flat(1.5)` is equivalent to `.flat(1)`.
@@ -96,6 +104,20 @@ impl Rule for PreferArrayFlatMap {
96104
}
97105
}
98106

107+
/// Returns true if the object of the method call is `Children` or `React.Children`.
108+
fn is_ignored_call_expression(call_expr: &CallExpression) -> bool {
109+
let Some(member_expr) = call_expr.callee.get_member_expr() else {
110+
return false;
111+
};
112+
match member_expr.object().get_inner_expression() {
113+
Expression::Identifier(ident) => IGNORE_OBJECTS.contains(&ident.name.as_str()),
114+
Expression::StaticMemberExpression(mem) => {
115+
IGNORE_OBJECTS.contains(&mem.property.name.as_str())
116+
}
117+
_ => false,
118+
}
119+
}
120+
99121
#[test]
100122
fn test() {
101123
use crate::tester::Tester;
@@ -125,6 +147,9 @@ fn test() {
125147
("const bar = [[1],[2],[3]].map(i => [i]).flat(+1)", None),
126148
("const bar = [[1],[2],[3]].map(i => [i]).flat(foo)", None),
127149
("const bar = [[1],[2],[3]].map(i => [i]).flat(foo.bar)", None),
150+
// Allowed
151+
("Children.map(children, fn).flat()", None), // `import {Children} from 'react';`
152+
("React.Children.map(children, fn).flat()", None),
128153
];
129154

130155
let fail = vec![

0 commit comments

Comments
 (0)