Skip to content

Instantly share code, notes, and snippets.

@tomasswood
Created November 13, 2018 21:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tomasswood/3cd7ca136421747787f921c0f2030d6d to your computer and use it in GitHub Desktop.
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
/**
* 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 };
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