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

标签 javascript currying

我开始学习 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/

相关文章:

javascript - 绑定(bind)函数的意外行为

function - scala隐式类方法类型不匹配在reduce与函数currying的非隐式方法中

javascript - 使用 Javascript 更改 div 的背景图像

javascript - 无法在 JavaScript 中进行乘法运算

javascript - 如何分割数组内的数据

javascript - 在所有平台(包括 iOS、ANDROID)的 Delphi XE6 上通过 javascript 从 TWebBrowser 回调 Delphi 函数?

javascript - 检查 jquery 的多个输入的值是否为空的更短方法

java - Lambda 作为 Predicate 接口(interface)中方法的组合,如果它被写成一条语句则无法编译

Scheme/DrRacket - 带 foldr 的 map 功能

scala - Scala 中的柯里化(Currying)示例