我开始学习curried函数,并认为有一个函数允许我在类似的dom元素组(输入组或属于同一个父类的选择组)中找到满足的函数是有用的。回调函数。
我的目标是有一个curried函数,我可以传递一个DOM元素的id(parentId
),其中包含元素(使用类groupClassName
)我想运行callback
。我设法让curried函数工作,但我找不到一种方法来传递array.prototype
方法作为参数。目前,该方法(无论是.filter还是.find方法)在函数中是硬编码的。我认为如果我可以将其作为参数传递并且只有一个curried函数,我可以决定使用哪种原型方法,那将会更加干燥。
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));
};
我正在使用的回调示例是这样的:
export function altDateGroupEmpty(group) {
const selects = Array.from(group.getElementsByTagName("select"));
return selects.every(select => select.value === "");
}
现在我无法传递数组原型方法(过滤器或查找),我必须创建两个不同的curried函数filterGroups
和findGroups
。这些工作按预期工作,但我想将数组原型方法作为额外参数传递,以使此代码更干燥。
我对这种情况非常开放,因为我刚刚开始了解如何在我的代码中使用curried函数
你可以为原型采用另一个参数,并使用Function#call
用thisArg
调用原型。
const perform = parentId => groupClassName => prototype => callback => {
const groups = Array.from(document.getElementById(parentId).getElementsByClassName(groupClassName));
return prototype.call(groups, callback);
};
打电话给
perform('foo')('grey')(Array.prototype.filter)(g => true);