Refactor Javascript code