简体   繁体   中英

how to pass Array.prototype methods as parameters in curried functions

I'm beginning to learn about curried functions and thought it would be useful to have a function which allows me to find, among groups of similar dom elements (groups of inputs or of selects that belong to the same parent),the ones that satisfy a callback function.

My objective is to have a curried function where I can pass the id ( parentId ) of a DOM element that contains the elements (with class groupClassName ) I want to run the callback on. I have managed to get the curried function working but I cannot find a way to pass the array.prototype method as a parameter. For now the method (be it a .filter or .find method) is hardcoded in the functions. I thought it would be more DRY if I could pass that in as a parameter and have only one curried function where I can decide which prototype method to use.

const filterGroups = parentId => groupClassName => callback => {
  const groups = Array.from(
    document.getElementById(parentId).getElementsByClassName(groupClassName)
  );
  return groups.filter(group => callback(group));
};
const findGroups = parentId => groupClassName => callback => {
  const groups = Array.from(
    document.getElementById(parentId).getElementsByClassName(groupClassName)
  );
  return groups.find(group => callback(group));
};

an example of a callback I'm using would be this:

export function altDateGroupEmpty(group) {
  const selects = Array.from(group.getElementsByTagName("select"));
  return selects.every(select => select.value === "");
}

for now I cannot pass the array prototype method (filter or find) and I have to create two distinct curried functions filterGroups and findGroups . These work as expected but I would like to pass the array prototype method as an extra parameter to make this code more dry.

I'm very much open to different takes on this situation as I'm just starting to understand how to use curried functions in my code

You could take another parameter for the prototype and use Function#call for calling the prototype with thisArg .

const perform = parentId => groupClassName => prototype => callback => {
    const groups = Array.from(document.getElementById(parentId).getElementsByClassName(groupClassName));
    return prototype.call(groups, callback);
};

call with

perform('foo')('grey')(Array.prototype.filter)(g => true);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM