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).
Avoid spreading the accumulator inside reduce
Build maps/objects with a Map and a for-loop (or a single mutated object) instead of spreading the accumulator each iteration in reduce, which is O(n^2).
Bad example
| 1 | function indexImagesById( |
| 2 | articles: Article[], |
| 3 | ): Record<string, string | undefined> { |
| 4 | return articles.reduce<Record<string, string | undefined>>( |
| 5 | (acc, article) => ({ |
| 6 | ...acc, |
| 7 | [article.id]: article.leadImage?.originalUrl, |
| 8 | }), |
| 9 | {}, |
| 10 | ); |
| 11 | } |
Explanation (EN)
Spreading `...acc` on every iteration re-copies all previously added keys, so building the map costs O(n^2) time and allocates a fresh object per element. On large article lists this becomes a real hotspot for no readability benefit.
Objašnjenje (HR)
Sirenje `...acc` u svakoj iteraciji ponovno kopira sve prethodno dodane kljuceve, pa izgradnja mape kosta O(n^2) vremena i alocira novi objekt po elementu. Na velikim listama clanaka to postaje stvarno usko grlo bez ikakve koristi za citljivost.
Good example
| 1 | function indexImagesById( |
| 2 | articles: Article[], |
| 3 | ): Map<string, string | undefined> { |
| 4 | const result = new Map<string, string | undefined>(); |
| 5 | for (const article of articles) { |
| 6 | result.set(article.id, article.leadImage?.originalUrl); |
| 7 | } |
| 8 | return result; |
| 9 | } |
Explanation (EN)
A Map populated by a single pass is O(n), allocates once, and is clearer about intent (a keyed lookup). If a plain object is required by the contract, mutate one object in the loop rather than spreading.
Objašnjenje (HR)
Mapa popunjena jednim prolazom je O(n), alocira se jednom i jasnije izrazava namjeru (pretrazivanje po kljucu). Ako ugovor zahtijeva obicni objekt, mutiraj jedan objekt u petlji umjesto sirenja.
Exceptions / Tradeoffs (EN)
For tiny, fixed-size collections the difference is irrelevant; readability concerns can dominate there. Spread-in-reduce is also fine when you specifically need a new immutable object per step.
Iznimke / Tradeoffi (HR)
Za male zbirke fiksne velicine razlika je nebitna; tamo moze prevladati citljivost. Sirenje u reduce je takodjer u redu kad ti specificno treba novi nepromjenjiv objekt po koraku.