Refactored javascript code