Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Rule proposal: Prefer Array.from() callback for list comprehensions #2550

Open
geoffswift opened this issue Feb 2, 2025 · 0 comments
Open

Comments

@geoffswift
Copy link

geoffswift commented Feb 2, 2025

Description

I've seen a bunch of examples where Array(n).keys() is used as part of a list comprehension. Since keys() here returns an iterator the typical form is like Array.from(Array(n).keys()) or [...Array(n).keys()]

This has the overhead of extra intermediate array(s) and using the callback for Array.from() although more verbose is the best performer.

See examples for details.

Examples

// ❌
Array.from(Array(n).keys())

// ❌
[...Array(n).keys()]

// ✅
Array.from({ length: n }, (_, i) => i)
// ❌
Array.from(Array(n).keys()).map((i) => ({ id: i, }));

// ❌
[...Array(n).keys()].map((i) => ({ id: i, }));

// ✅
Array.from({ length: n }, (_, i) => ({ id: i, }))

Proposed rule name

prefer-callback-for-list-comprehension

Additional Info

No response

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant