Skip to content

Add Array.from() support to prefer-set-size rule#2857

Merged
sindresorhus merged 3 commits intosindresorhus:mainfrom
costajohnt:fix/prefer-set-size-array-from
Feb 10, 2026
Merged

Add Array.from() support to prefer-set-size rule#2857
sindresorhus merged 3 commits intosindresorhus:mainfrom
costajohnt:fix/prefer-set-size-array-from

Conversation

@costajohnt
Copy link
Contributor

Fixes #2843

The prefer-set-size rule now also detects Array.from(set).length and suggests set.size instead, matching the existing behavior for [...set].length.

Changes

Rule (rules/prefer-set-size.js):

  • Added detection for Array.from(set).length where set is either new Set(...) directly or a const variable initialized to new Set(...)
  • Correctly skips when Array.from has a second argument (mapping function), uses optional chaining, or the argument is not a Set
  • Autofix replaces Array.from(set).length with set.size, suppressing the fix when comments would be lost

Tests (test/prefer-set-size.js):

  • 16 new valid cases covering Array.from edge cases (wrong object, optional chaining, second argument, non-Set types, non-const variables)
  • 6 new invalid cases covering direct new Set, const variable reference, nested parentheses, outer parentheses, and comment handling

Detect `Array.from(set).length` and suggest `set.size` instead,
matching the existing behavior for `[...set].length`.

Fixes sindresorhus#2843

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
@costajohnt costajohnt force-pushed the fix/prefer-set-size-array-from branch from 629006d to 3f32fbf Compare February 5, 2026 22:04
@sindresorhus sindresorhus merged commit e556143 into sindresorhus:main Feb 10, 2026
18 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

prefer-set-size rule does not catch Array.from() usage for converting a set to an array

3 participants