gpt4 book ai didi

javascript - 如何在柯里化(Currying)函数中将 Array.prototype 方法作为参数传递

转载 作者:行者123 更新时间:2023-11-30 14:04:45 25 4
gpt4 key购买 nike

我开始学习 curried 函数,并认为有一个函数可以让我在相似的 dom 元素组(属于同一父元素的输入或选择组)中找到有用的函数,那些满足回调函数的。

我的目标是拥有一个柯里化(Currying)函数,我可以在其中传递包含我想要的元素(具有类 groupClassName)的 DOM 元素的 ID (parentId)运行 回调。我已经设法使 curried 函数正常工作,但我找不到将 array.prototype 方法作为参数传递的方法。现在,该方法(无论是 .filter 还是 .find 方法)都硬编码在函数中。我认为,如果我可以将其作为参数传入并且只有一个柯里化(Currying)函数,我可以在其中决定使用哪个原型(prototype)方法,那会更 DRY。

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 === "");
}

目前我无法传递数组原型(prototype)方法(filter 或 find),我必须创建两个不同的柯里化(Currying)函数 filterGroupsfindGroups。这些按预期工作,但我想将数组原型(prototype)方法作为额外参数传递,以使这段代码更加枯燥。

我对这种情况的不同看法非常开放,因为我才刚刚开始理解如何在我的代码中使用柯里化(Currying)函数

最佳答案

您可以为原型(prototype)采用另一个参数并使用 Function#call用于使用 thisArg 调用原型(prototype)。

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);

关于javascript - 如何在柯里化(Currying)函数中将 Array.prototype 方法作为参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55647861/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com