Refactor countBy