Refactor JavaScript code to methods so it's more readable