Refactoring javascript code