Refactor the code with my own understanding of merge function