Refactoring my spaghetti js