What about extracting this to a function rather than repeating this logic many times?