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).
Build lookup Maps with the Map constructor and entry tuples
Prefer `new Map(items.map(x => [x.key, x]))` over an imperative for-loop with repeated map.set calls to build a lookup Map.
Bad example
| 1 | const eventsMap = new Map<number, Event>(); |
| 2 | for (const event of events) { |
| 3 | eventsMap.set(event.id, event); |
| 4 | } |
| 5 | return eventsMap; |
Explanation (EN)
Allocating an empty Map and mutating it in a loop is three lines of boilerplate for a transformation that is a single expression.
Objašnjenje (HR)
Alociranje praznog Map-a i njegova mutacija u petlji je tri linije suvisnog koda za transformaciju koja je jedan izraz.
Good example
| 1 | return new Map(events.map((event) => [event.id, event])); |
Explanation (EN)
The Map constructor accepts an iterable of [key, value] entry tuples, so mapping the array straight into the constructor expresses the intent in one declarative line with no intermediate mutation.
Objašnjenje (HR)
Map konstruktor prima iterabilan niz [kljuc, vrijednost] parova, pa mapiranje niza direktno u konstruktor izrazava namjeru u jednoj deklarativnoj liniji bez medjumutacije.
Exceptions / Tradeoffs (EN)
If keys can collide and you need custom merge logic (e.g. keep the first occurrence, or combine values), the explicit loop is clearer. Balance against prefer-record-over-map-for-simple-indexing: when you do build a Map, construct it from entry tuples rather than a mutating for-loop.
Iznimke / Tradeoffi (HR)
Ako se kljucevi mogu sudariti i treba vam prilagodjena logika spajanja (npr. zadrzi prvu pojavu ili kombiniraj vrijednosti), eksplicitna petlja je jasnija.