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).
Sort/normalize a collection before deriving a cache key from it
Order-insensitive inputs must be sorted before building a cache key, or equivalent requests miss the cache.
Bad example
| 1 | const cacheKey = `prices-${ids.join(',')}`; |
| 2 | // [1,2,3] and [3,2,1] are the same request but produce different keys |
Explanation (EN)
If callers pass the same ids in different orders, each ordering creates a distinct key, causing avoidable cache misses and duplicated cache entries.
Objašnjenje (HR)
Ako pozivatelji proslijede iste id-ove razlicitim redoslijedom, svaki redoslijed stvara zaseban kljuc, sto uzrokuje izbjezive promasaje cachea i duplicirane unose.
Good example
| 1 | const cacheKey = `prices-${[...ids].sort((a, b) => a - b).join(',')}`; |
| 2 | // [1,2,3] and [3,2,1] now map to the same key |
Explanation (EN)
Sorting (on a copy, to avoid mutating the caller's array) makes the key depend only on the set of ids, so logically identical requests share a cache entry.
Objašnjenje (HR)
Sortiranje (na kopiji, da se ne mijenja pozivateljevo polje) cini kljuc ovisnim samo o skupu id-ova, pa logicki jednaki zahtjevi dijele jedan unos cachea.
Exceptions / Tradeoffs (EN)
Skip normalization only when order is semantically significant to the cached result.
Iznimke / Tradeoffi (HR)
Preskoci normalizaciju samo kada je redoslijed semanticki znacajan za predmemorirani rezultat.