0
Convert imperative loop-heavy code to functional style without losing clarity
⁂auto-checked, 4 days oldAauraNovice
The prompt
Rewrite this code from an imperative, loop-and-mutation style into a functional style using language's idiomatic map/filter/reduce (or equivalent) constructs. Constraints:
1. Only do this where it genuinely improves readability; if a loop is already the clearest way to express the logic (e.g. it has early exits, multiple accumulators, or complex control flow), say so and leave it as a loop rather than forcing a functional rewrite that would be harder to read.
2. Preserve exact behavior including edge cases (empty input, short-circuit behavior).
3. Avoid deeply chained one-liners that sacrifice readability for cleverness; prefer named intermediate variables over a 5-deep chain.
4. Note any performance implications (e.g. multiple passes over the array instead of one) and whether that matters given the expected data size.
5. Show before and after, and a one-line justification for each change.
Code: code
Expected data size / performance sensitivity: data_size_context
Where it has been run
| Model | Version | People | Broke | Auto | Last |
|---|---|---|---|---|---|
| Claude | Haiku 4.5 | 0 | 0 | 1/1 | 4 days ago |
Example output
Before: a for-loop building `results` while also tracking a separate `errorCount`, with a `continue` on invalid rows.
After:
```js
const validRows = rows.filter(isValidRow);
const results = validRows.map(toRecord);
const errorCount = rows.length - validRows.length;
```
Justification: splitting into named steps makes each transformation independently testable and the intent ('filter, then transform, then count what got dropped') reads top to bottom instead of being interleaved in loop state.
Left as a loop: the second function, `aggregate_stats`, keeps its imperative form because it accumulates three different running values (sum, max, and a rolling average that depends on the previous iteration's average) with an early break on a sentinel value, a functional reduce would need a compound accumulator object that's harder to follow than the current loop.
Performance note: the rewritten version does two passes (filter then map) instead of one; given you said data size is under 500 rows per request, this is negligible and not worth a single-pass reduce that would sacrifice the readability gain.
0 comments
Sign in to comment or report what this prompt did for you.
Sign inNo comments yet. Run the prompt and report what you got.