Rules Hub
Coding Rules Library
Prefer flatMap for combined mapping and filtering
Use flatMap to transform and filter items in a single pass instead of chaining map and filter.
Bad example
| 1 | const rawIds = ['1', '2', 'invalid', '3']; |
| 2 |
|
| 3 | // Iterates twice: once to convert, once to filter |
| 4 | const ids = rawIds |
| 5 | .map((id) => Number(id)) |
| 6 | .filter((id) => Number.isFinite(id)); |
Explanation (EN)
Chaining .map() and .filter() creates an intermediate array and iterates over the collection twice. This separates the transformation logic from the validation logic, which can be less efficient and harder to follow for complex types.
Objašnjenje (HR)
Lančanje .map() i .filter() stvara privremeni niz i iterira kroz kolekciju dva puta. Ovo razdvaja logiku transformacije od validacije, što može biti manje učinkovito i teže za praćenje kod složenijih tipova.
Good example
| 1 | const rawIds = ['1', '2', 'invalid', '3']; |
| 2 |
|
| 3 | // Iterates once: returns [] to exclude, [value] to include |
| 4 | const ids = rawIds.flatMap((id) => { |
| 5 | const num = Number(id); |
| 6 | return Number.isFinite(num) ? [num] : []; |
| 7 | }); |
Explanation (EN)
Using .flatMap() combines the mapping and filtering into a single pass. By returning an empty array [], you effectively filter out the item, and by returning [value], you keep it. This is a standard functional programming pattern for 'filterMap' operations.
Objašnjenje (HR)
Korištenje .flatMap() kombinira mapiranje i filtriranje u jedan prolaz. Vraćanjem praznog niza [] učinkovito filtrirate stavku, a vraćanjem [value] je zadržavate. Ovo je standardni obrazac funkcionalnog programiranja za 'filterMap' operacije.
Notes (EN)
While map().filter() is readable for very simple cases, flatMap is generally preferred when the transformation might result in invalid states that need immediate removal.
Bilješke (HR)
Iako je map().filter() čitljiv za vrlo jednostavne slučajeve, flatMap se općenito preferira kada transformacija može rezultirati neispravnim stanjima koja treba odmah ukloniti.