refactoring: loop over the range just once