Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor Key Handling to Use Lookup Table for Arrow Keys #118

Open
dmcote-1991 opened this issue Sep 25, 2024 · 0 comments
Open

Refactor Key Handling to Use Lookup Table for Arrow Keys #118

dmcote-1991 opened this issue Sep 25, 2024 · 0 comments

Comments

@dmcote-1991
Copy link
Contributor

Refactor Key Handling in Snake Game to Use Lookup Table for Arrow Keys

I suggest refactoring the handleArrowKeys method to replace the current switch statement with a more maintainable and concise lookup table for handling key presses. This approach follows modern JavaScript best practices and improves code readability.

Proposed Changes:

  • Replace the switch statement with a keyToDirection object that maps key codes to movement directions.
  • Use the ?? (nullish coalescing) operator to handle invalid key presses more cleanly.
  • Ensure const and let are used for block-scoped variables to improve scoping and maintainability.

Benefits:

  • Simplifies the key handling logic, making it easier to read and maintain.
  • Enhances flexibility for future key mappings or modifications.
  • Adheres to modern JavaScript standards, leading to better performance and clarity.

Here is an example of the proposed refactor:

const keyToDirection = {
    37: 3, // Left arrow
    65: 3, // 'A' key
    38: 0, // Up arrow
    87: 0, // 'W' key
    39: 1, // Right arrow
    68: 1, // 'D' key
    40: 2, // Down arrow
    83: 2  // 'S' key
};

const directionFound = keyToDirection[keyNum] ?? -1;
@dmcote-1991 dmcote-1991 changed the title Refactor Key Handling in Snake Game to Use Lookup Table for Arrow Keys Refactor Key Handling to Use Lookup Table for Arrow Keys Sep 25, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant