Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

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

Copy link
Copy link
@dmcote-1991

Description

@dmcote-1991
Issue body actions

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;
Reactions are currently unavailable

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      Morty Proxy This is a proxified and sanitized view of the page, visit original site.