Extracting the loop into its own function