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).
Track serialized length while building a bounded list
When trimming a list to a serialized-length limit, update a running length including separators instead of repeatedly serializing the remaining array inside a loop.
Bad example
| 1 | export function boundedPrefix(items: readonly string[], maxLength: number): string { |
| 2 | const kept = [...items]; |
| 3 | while (kept.length && kept.join(',').length > maxLength) kept.pop(); |
| 4 | return kept.join(','); |
| 5 | } |
Explanation (EN)
Each removal joins and measures the whole remaining list, repeating work and allocations.
Objašnjenje (HR)
Svako uklanjanje ponovno spaja i mjeri cijeli preostali popis, uz ponovljeni rad i alokacije.
Good example
| 1 | export function boundedPrefix(items: readonly string[], maxLength: number): string { |
| 2 | const kept: string[] = []; |
| 3 | let length = 0; |
| 4 | for (const item of items) { |
| 5 | const nextLength = length + (kept.length ? 1 : 0) + item.length; |
| 6 | if (nextLength > maxLength) break; |
| 7 | kept.push(item); |
| 8 | length = nextLength; |
| 9 | } |
| 10 | return kept.join(','); |
| 11 | } |
Explanation (EN)
One pass accounts for each item and delimiter, then serialization happens once.
Objašnjenje (HR)
Jedan prolaz uračunava svaku stavku i razdjelnik, a spajanje se izvršava jednom.
Notes (EN)
Applies when profiling or the input bound justifies removing repeated linear work. Match the limit unit: string.length counts UTF-16 code units, not UTF-8 bytes. An empty prefix is valid only if the caller explicitly supports it. Do not add memoization automatically for cheap bounded computations.
Bilješke (HR)
Primijeni kada mjerenje ili veličina ulaza opravdava uklanjanje ponovljenog linearnog rada. Poštuj jedinicu ograničenja: string.length broji UTF-16 jedinice, ne UTF-8 bajtove. Prazan prefiks vrijedi samo ako ga pozivatelj podržava. Nemoj automatski memoizirati jeftin ograničen izračun.
Exceptions / Tradeoffs (EN)
For tiny inputs a simpler implementation may be clearer. Escaping or variable-length encoding requires measuring encoded items and delimiters, not their raw source lengths.
Iznimke / Tradeoffi (HR)
Za vrlo male ulaze jednostavnija implementacija može biti čitljivija. Escaping ili kodiranje promjenjive duljine zahtijeva mjerenje kodiranih stavki i razdjelnika.