javascript-prefer-set-size-over-length
Replace incorrect or non-idiomatic `set.length` reads with `set.size` for variables/expressions statically known to be `Set` instances in JavaScript/TypeScript codebases, improving correctness and code quality.
# javascript-prefer-set-size-over-length
Replace incorrect `Set` cardinality reads like `set.length` with `set.size` when the receiver is statically proven to be a built-in `Set` or `ReadonlySet`.
## What It Rewrites
- `const s = new Set(values); s.length` -> `s.size`
- `function f(s: Set<number>) { return s.length; }` -> `return s.size`
- `maybeSet?.length` -> `maybeSet?.size` when the type is `Set | nullish`
- `set['length']` -> `set.size` by default, or `set['size']` with `--param computed_style=computed`
- Reads narrowed by `instanceof Set`, `Object.prototype.toString.call(x) === '[object Set]'`, or a user-defined type guard returning `x is Set<...>`
- Safe `const` aliases such as `const alias = set`
- `this.cache.length` and typed property reads when the property is declared as `Set<...>` or `ReadonlySet<...>`
## Safety Rules
- Skips unknown or ambiguous receivers
- Skips arrays, strings, functions, typed arrays, and other normal `.length` reads
- Skips write/update/delete contexts such as `set.length = 1`, `set.length++`, and `delete set.length`
- Skips dynamic keys like `set[key]`
- Skips visible subclass overrides such as `new CustomSet().length`
- Excludes `node_modules`, `dist`, `build`, `coverage`, and `vendor` paths by default
## Usage
```bash
# Run the published codemod
npx codemod javascript-prefer-set-size-over-length -t /path/to/repo
# Run the local package
pnpm dlx codemod@latest workflow run -w . -t /path/to/repo
# Preserve computed access for string-literal keys
pnpm dlx codemod@latest workflow run -w . -t /path/to/repo --param computed_style=computed
```
## Development
```bash
pnpm test
pnpm run validate
pnpm run check-types
```
## License
MIT