sindresorhus/eslint-plugin-unicorn

Rule proposal: Prefer explicit array check over `Array#flat()`.

Closed

#1,719 opened on Feb 8, 2022

 (4 comments) (4 reactions) (0 assignees)JavaScript (468 forks)user submission
help wantednew rule

Repository metrics

Stars
 (5,022 stars)
PR merge metrics
 (Avg merge 1d 16h) (399 merged PRs in 30d)

Description

Description

When a function accepts a single or multiple things. Though [foo].flat() is shorter and nicer, but it's not very clear to me.

I prefer Array.isArray(foo) ? foo : [foo]. If the array need to be cloned Array.isArray(foo) ? [...foo] : [foo].

But if the variable name is something like nameOrNames, [nameOrNames].flat() looks clear to me, maybe we can add an exception.

Fail

items = [items].flat();

Pass

items = Array.isArray(items) ? items : [items];
items = Array.isArray(items) ? [...items] : [items];
items = [...(Array.isArray(items) ? items : [items])];
const names = [nameOrNames].flat();

Contributor guide