Created
November 13, 2018 21:27
-
-
Save tomasswood/3cd7ca136421747787f921c0f2030d6d to your computer and use it in GitHub Desktop.
Add a param to an action, eg. Overload an action with a set parameter at the start
This file contains 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 that takes a param, and uses it as the first argument for another function | |
* | |
* @param key | |
* @param action | |
* @returns {function(...[*]): *} | |
*/ | |
const addParamToAction = (param, action) => { | |
return (...rest) => action(param, ...rest); | |
}; | |
/** | |
* Use this factory to loop through an object of functions and modify each | |
* function so that the first parameter is set as a specified param | |
* | |
* @param key | |
* @param actionsGroup | |
* @returns {function(...[*]): *} or object | |
*/ | |
const addParamToActions = (param, actionsGroup) => { | |
let exports = {}; | |
// If we are just provided a function, treat it as if we called 'createNamedAction' | |
if (typeof actionsGroup === 'function') { | |
return createNamedAction(key, actionsGroup); | |
} else if (typeof actionsGroup === 'object') { | |
// Loop through all properties in our actions list | |
for (const action in actionsGroup) { | |
if (actionsGroup.hasOwnProperty(action)) { | |
// If the property is a function | |
if (typeof actionsGroup[action] === 'function') { | |
// Call our higher order function to overload the first param with the provided param | |
exports[action] = addParamToAction(param, actionsGroup[action]); | |
} else { | |
exports[action] = actionsGroup[action]; // Leave as is | |
} | |
} | |
} | |
} | |
return exports; | |
}; | |
export { addParamToAction, addParamToActions }; |
This file contains 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
const namedAction = addParamToAction(ACTION_KEY, action); | |
const namedActions = addParamToActions(ACTION_KEY, actionList); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment