Skip to content

Instantly share code, notes, and snippets.

@gabemeola
Last active May 14, 2019 23:37
Show Gist options
  • Save gabemeola/54d25d32f702b8808108102c0c067038 to your computer and use it in GitHub Desktop.
Save gabemeola/54d25d32f702b8808108102c0c067038 to your computer and use it in GitHub Desktop.
Higher order function which handles key presses
/**
* 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;
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