Optimized some code with functional programming approach