how to refactor javascript code