Refactoring chart javascript code