A general "recipe" for making repeated code into a function is to make the common parts the body of the function, and make the parts that differ parameters of the function.
sorry .. i don't understand the structure of the function in your head .. i'm barely hanging on here