Refactoring handleKeys function