Skip to content

Commit

Permalink
bunch of key helpers (#74)
Browse files Browse the repository at this point in the history
  • Loading branch information
Kashargul authored Jan 26, 2025
1 parent ed767c8 commit 9560893
Showing 1 changed file with 81 additions and 0 deletions.
81 changes: 81 additions & 0 deletions lib/common/keys.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,25 +21,32 @@
*
*/
export enum KEY {
A = 'a',
Alt = 'Alt',
Backspace = 'Backspace',
Control = 'Control',
D = 'd',
Delete = 'Delete',
Down = 'ArrowDown',
E = 'e',
End = 'End',
Enter = 'Enter',
Esc = 'Esc',
Escape = 'Escape',
Home = 'Home',
Insert = 'Insert',
Left = 'ArrowLeft',
N = 'n',
PageDown = 'PageDown',
PageUp = 'PageUp',
Right = 'ArrowRight',
S = 's',
Shift = 'Shift',
Space = ' ',
Tab = 'Tab',
Up = 'ArrowUp',
W = 'w',
Z = 'z',
}

/**
Expand All @@ -56,3 +63,77 @@ export enum KEY {
export function isEscape(key: string): boolean {
return key === KEY.Esc || key === KEY.Escape;
}

/**
* ### isAlphabetic
*
* Checks if the user has hit any alphabetic key (a - z)
*
* @param key - the key to check, typically from event.key
* @returns true if key is in the range of a-z
*/
export function isAlphabetic(key: string): boolean {
return key >= KEY.A && key <= KEY.Z;
}

/**
* ### isNumeric
*
* Checks if the user has hit any numeric key (0 - 9)
*
* @param key - the key to check, typically from event.key
* @returns true if key is in the range of 0 - 9
*/
export function isNumeric(key: string): boolean {
return key >= '0' && key <= '9';
}

/**
* ### isCardinal
*
* Checks if the user has hit any cardinal key (n s w e)
*
* @param key - the key to check, typically from event.key
* @returns true if key matches any cardinal n s w e
*/
export function isCardinal(key: string): boolean {
return key === KEY.N || key === KEY.S || key === KEY.W || key === KEY.E;
}

/**
* ### isArrow
*
* Checks if the user has hit any arrow key
*
* @param key - the key to check, typically from event.key
* @returns true if key matches any arrow keys
*/
export function isArrow(key: string): boolean {
return (
key === KEY.Up || key === KEY.Down || key === KEY.Left || key === KEY.Right
);
}

/**
* ### isWasd
*
* Checks if the user has hit any w a s d key
*
* @param key - the key to check, typically from event.key
* @returns true if key matches any w a s d
*/
export function isWasd(key: string): boolean {
return key === KEY.W || key === KEY.A || key === KEY.S || key === KEY.D;
}

/**
* ### isMovement
*
* Checks if the user has hit any movement key (w a s d and arrow keys)
*
* @param key - the key to check, typically from event.key
* @returns true if key matches any movement key w a s d and arrow keys
*/
export function isMovement(key: string): boolean {
return isWasd(key) || isArrow(key);
}

0 comments on commit 9560893

Please sign in to comment.