refactoring replacing ifs with loop