refactored the compare function to remove redundant code