Last active
May 14, 2019 23:37
-
-
Save gabemeola/54d25d32f702b8808108102c0c067038 to your computer and use it in GitHub Desktop.
Higher order function which handles key presses
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Higher order function which handles | |
* key presses "onKeyDown". | |
* | |
* Passes event to function. | |
* | |
* @param {Function} fn - Function to be invoked with event | |
* @return {function(Event): any} | |
*/ | |
const clickKeyPress = (fn) => (ev) => { | |
// Return out if user used "onKeyDown" | |
// but didn't use the enter key | |
if (ev.keyCode && (ev.keyCode !== 13 || ev.key !== 'Enter')) return; | |
// eslint-disable-next-line consistent-return | |
return fn(ev); | |
}; | |
export default clickKeyPress; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
type Event = { | |
keyCode?: number | |
[key: string]: any; | |
}; | |
type EventFn = (ev: Event) => any; | |
/** | |
* Higher order function which handles | |
* key presses "onKeyDown". | |
* | |
* Passes event to function. | |
*/ | |
const clickKeyPress = <T extends EventFn>(fn: T) => <E extends Event>(ev: E): ReturnType<T> | void => { | |
// Return out if user used "onKeyDown" | |
// but didn't use the enter key | |
if ('keyCode' in ev && (ev.keyCode !== 13 || ev.key !== 'Enter')) return; | |
// eslint-disable-next-line consistent-return | |
return fn(ev); | |
}; | |
export default clickKeyPress; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment