Replace ternaries with a looping function