javascript - 在 ramda 中调用具有相同参数的函数列表

标签 javascript ramda.js

假设我有一个函数列表,我想用相同的参数调用这些函数并获得结果列表。这是我的 setup :

let input = 2
let fns = [add(2), add(3), add(4)]

map(x => x(input), fns)
// this is what I want. Outputs [4, 5, 6]

但我不太喜欢箭头函数的使用(纯粹出于风格原因),所以我想将其重写为,

map(call(__, input), fns)
// this doesn't work and produces [[Function],[Function],[Function]]

我不明白为什么 x => x(input) 不等同于 call(__, input)。我的想法是,call(__, input) 将返回一个函数,该函数将使用 input 调用其第一个参数。

你能解释一下我做错了什么吗?我的直觉是我误解了 __ 的用法。我该如何使用 call 或其他一些内置函数来优雅地编写它?

我也试过了,

// this also works and produces [4, 5, 6]
map(flip(call)(input), fns)

但由于风格原因,这也不适合我。我觉得我在用 flip 强行塞进一些东西,而且我也不喜欢连续的函数调用 (...)(...)

最佳答案

您正在寻找R.juxt :

juxt applies a list of functions to a list of values.

const { add, juxt } = R

const input = 2
const fns = [add(2), add(3), add(4)]

const addTo = juxt(fns)

const result = addTo(input)

console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.27.0/ramda.js"></script>

关于javascript - 在 ramda 中调用具有相同参数的函数列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61698343/

相关文章:

javascript - 从数组中删除一个对象,然后更新所有对象的属性

javascript - 重构 if else 语句以使用 Ramda.js 并将键值对分解为对象记录

javascript - 在 javascript 中使用相同的参数组成链式函数

ramda.js - lambda : How to filter based on a value in a nested array

javascript - 在 Rollup 构建的 Electron 应用程序中导入 Ramda 会导致错误

javascript - 使用 Selenium 捕获 REST 调用

javascript - 未捕获的类型错误 : Cannot read property 'getData' of undefined

javascript - 如何使用 jQuery/media 查询在窗口调整大小时重新排序列表项

javascript - module.exports.report.logon 不是一个函数

javascript - 删除javascript中的文本输入