如何在柯里化函数中将 Array.prototype 方法作为参数传递
how to pass Array.prototype methods as parameters in curried functions
我开始学习柯里化函数,我认为如果有一个函数可以让我在相似的 dom 元素组(输入组或属于同父),满足回调函数的。
我的 objective 有一个咖喱函数,我可以在其中传递包含元素的 DOM 元素的 ID (parentId
)(class groupClassName
) 我要运行上callback
。我已经设法使 curried 函数正常工作,但我找不到将 array.prototype
方法作为参数传递的方法。现在,该方法(无论是 .filter 还是 .find 方法)都硬编码在函数中。我认为如果我可以将其作为参数传递并且只有一个柯里化函数,我可以在其中决定使用哪种原型方法,那就更干了。
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 === "");
}
目前我无法传递数组原型方法(过滤或查找),我必须创建两个不同的柯里化函数 filterGroups
和 findGroups
。这些按预期工作,但我想将数组原型方法作为额外参数传递,以使这段代码更加枯燥。
我对这种情况的不同看法非常开放,因为我才刚刚开始了解如何在我的代码中使用柯里化函数
您可以为原型获取另一个参数,并使用 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);
我开始学习柯里化函数,我认为如果有一个函数可以让我在相似的 dom 元素组(输入组或属于同父),满足回调函数的。
我的 objective 有一个咖喱函数,我可以在其中传递包含元素的 DOM 元素的 ID (parentId
)(class groupClassName
) 我要运行上callback
。我已经设法使 curried 函数正常工作,但我找不到将 array.prototype
方法作为参数传递的方法。现在,该方法(无论是 .filter 还是 .find 方法)都硬编码在函数中。我认为如果我可以将其作为参数传递并且只有一个柯里化函数,我可以在其中决定使用哪种原型方法,那就更干了。
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 === "");
}
目前我无法传递数组原型方法(过滤或查找),我必须创建两个不同的柯里化函数 filterGroups
和 findGroups
。这些按预期工作,但我想将数组原型方法作为额外参数传递,以使这段代码更加枯燥。
我对这种情况的不同看法非常开放,因为我才刚刚开始了解如何在我的代码中使用柯里化函数
您可以为原型获取另一个参数,并使用 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);