假设我有一个函数列表,我想用相同的参数调用这些函数并获得结果列表。这是我的 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/