Mmohebifar

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.

javascripttypescriptsetcode-quality
Public
0 executions

Run locally

npx codemod javascript-prefer-set-size-over-length

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

Development

bash

License

MIT

Ready to contribute?

Build your own codemod and share it with the community.