Optimize flat_map to iterate once instead of twice