refactoring javascript code