Rules Hub
Coding Rules Library
Extract complex mapping logic into helper functions
Avoid complex inline callbacks in array methods like .map(); extract the logic into named helper functions for better readability.
Bad example
| 1 | const items = uniqueIds.map((id) => { |
| 2 | const details = detailsMap.get(id); |
| 3 | if (!details || !details.isActive) { |
| 4 | return null; |
| 5 | } |
| 6 |
|
| 7 | return { |
| 8 | id: details.id, |
| 9 | title: details.name.toUpperCase(), |
| 10 | url: `/product/${details.slug}`, |
| 11 | price: details.price ?? 0, |
| 12 | }; |
| 13 | }).filter((item): item is Item => item !== null); |
Explanation (EN)
The mapping logic is defined inline, making the main flow of the data transformation hard to follow. If the logic grows, this block becomes cluttered and harder to test.
Objašnjenje (HR)
Logika mapiranja definirana je 'inline', što otežava praćenje glavnog toka transformacije podataka. Ako logika postane složenija, ovaj blok postaje nepregledan i teži za testiranje.
Good example
| 1 | const mapIdToItem = (id: string, sourceMap: Map<string, Details>): Item | null => { |
| 2 | const details = sourceMap.get(id); |
| 3 | if (!details || !details.isActive) { |
| 4 | return null; |
| 5 | } |
| 6 |
|
| 7 | return { |
| 8 | id: details.id, |
| 9 | title: details.name.toUpperCase(), |
| 10 | url: `/product/${details.slug}`, |
| 11 | price: details.price ?? 0, |
| 12 | }; |
| 13 | }; |
| 14 |
|
| 15 | const items = uniqueIds |
| 16 | .map((id) => mapIdToItem(id, detailsMap)) |
| 17 | .filter((item): item is Item => item !== null); |
Explanation (EN)
The transformation logic is extracted into a named helper function `mapIdToItem`. The main transformation pipeline is now declarative and instantly readable.
Objašnjenje (HR)
Logika transformacije izdvojena je u imenovanu pomoćnu funkciju `mapIdToItem`. Glavni tok transformacije sada je deklarativan i trenutno čitljiv.