refactors the code, eliminating further duplication, but this time with lambdas