Refactored JavaScript code