0
Convert imperative loop-heavy code to functional style without losing clarity
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