Refactoring flip javascript