Refactor JS code