[AI] Remove code duplication from map component
Differential revision: D4235
I wanted to add new line and it send it instead. So here we go:
Remove duplication by moving loops into a function.
Optimise looping a bit by not recomputing part of variables dependent only on outer loop in inner loop.
let -> const where possible
Reviewed by: @bb
Comments by: @Stan