Rules Hub
Coding Rules Library
Rule priority, scope & exceptions
Use this to align rules with the senior-level structure (P0/P1/P2, scope, exceptions/tradeoffs).
Guard against duplicates before evicting from a bounded collection
When tracking items in a fixed-size sliding window, return early if the item already exists before evicting the oldest, so you neither drop a valid entry nor store duplicates.
Bad example
| 1 | private track(item: string): void { |
| 2 | if (this.recent.length >= MAX) { |
| 3 | this.recent.shift(); |
| 4 | } |
| 5 | this.recent.push(item); |
| 6 | } |
Explanation (EN)
Re-tracking an item that is already in the window evicts the oldest valid entry and then stores a duplicate, so the window ends up holding the same item twice and silently dropping a good one.
Objašnjenje (HR)
Ponovno dodavanje stavke koja je već u prozoru izbacuje najstariji valjani unos i zatim sprema duplikat, pa prozor na kraju drži istu stavku dvaput i tiho gubi jednu ispravnu.
Good example
| 1 | private track(item: string): void { |
| 2 | if (this.recent.includes(item)) return; |
| 3 | if (this.recent.length >= MAX) { |
| 4 | this.recent.shift(); |
| 5 | } |
| 6 | this.recent.push(item); |
| 7 | } |
Explanation (EN)
A membership check up front makes the operation idempotent: an already-tracked item is a no-op, so eviction only happens when genuinely adding something new.
Objašnjenje (HR)
Provjera članstva na početku čini operaciju idempotentnom: već praćena stavka ne radi ništa, pa do izbacivanja dolazi samo kad se stvarno dodaje nešto novo.
Notes (EN)
Applies to any LRU-style or recent-N window backed by an array or list where the same value can be added more than once.
Bilješke (HR)
Vrijedi za bilo koji LRU prozor ili prozor zadnjih N stavki temeljen na polju ili listi gdje se ista vrijednost može dodati više puta.
Exceptions / Tradeoffs (EN)
Not needed when the backing structure already enforces uniqueness (e.g. a Set) or when duplicates are intentional.
Iznimke / Tradeoffi (HR)
Nije potrebno kad pozadinska struktura već osigurava jedinstvenost (npr. Set) ili kad su duplikati namjerni.