You have a good instinct - “Don’t Repeat Yourself” is one of the mantras good programmers adhere to.
This could be where “object-oriented” programming could help out. Take a look at this post and associated code. It may serve as a path forward for you: