Javascript code refactoring