FlatMap Over Map Reduce
ID |
swift.flatmap_over_map_reduce |
Severity |
low |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Efficiency |
Language |
Swift |
Tags |
efficiency, idiomatic |
Description
Reports the .map(…).reduce([], +) chain. .flatMap(…) is
equivalent and runs in a single pass.
nodes.map { $0.children }.reduce([], +) // FLAW
nodes.flatMap { $0.children } // OK
Remediation
Replace the chain with flatMap:
let allChildren = nodes.flatMap { $0.children }
The rule only matches the exact (empty-array, +) reduce shape,
so it leaves alone reductions into scalars (.reduce(0, +)) and
non-empty initial values.