gptlint / gptlint

A linter with superpowers! 🔥 Use LLMs to enforce best practices across your codebase.
https://gptlint.dev
MIT License
213 stars 19 forks source link

Add efficient-data-structure-usage example #2

Closed mergebandit closed 4 months ago

mergebandit commented 4 months ago

👀

Use efficient data structures

Key Value
Name efficient-data-structure-usage
Level error
Fixable false
Tags performance
Languages javascript, typescript

Using appropriate data structures is crucial for writing efficient and performant code. This rule identifies cases where a more efficient data structure could be used to improve performance and readability.

When choosing a data structure, consider the following:

When suggesting a more efficient data structure, provide a clear explanation of the benefits and consider the trade-offs involved. If you are unsure whether a data structure usage violates the rule or if the suggested alternative is appropriate, err on the side of ignoring it or set confidence to low.

Bad

const uniqueItems = []
for (const item of items) {
  if (!uniqueItems.includes(item)) {
    uniqueItems.push(item)
  }
}

const counts = {}
for (const item of items) {
  if (counts[item]) {
    counts[item]++
  } else {
    counts[item] = 1
  }
}

Good

const uniqueItems = new Set(items)

const counts = new Map()
for (const item of items) {
  counts.set(item, (counts.get(item) || 0) + 1)
}
transitive-bullshit commented 4 months ago

Another option would be scoping this down to only focus on .includes or .find when a map/set/object lookup would be more efficient, but even there it's 95% of the time a premature optimization.