I need the functionality of Clojure's juxt
function in JavaScript. Is there a native function for this? We're using the Ramda functional JavaScript library . Is there a Ramda function with the juxt
functionality?
I know, of course, I can write this function myself. This is for educational purposes.
There are a few ways you could achieve this.
R.converge , which pipes the given value through each function in the provided list before using the result of each as the corresponding argument position of the function provided as the first argument to converge
- perhaps explained better with a diagram:
add = (a, b) => a + b
incr = a => a + 1
decr = a => a - a
double = converge(add, [incr, decr])
------ ---
5 ----| incr |- 6 -| a |
\ ------ | d |- 10
\-| decr |- 4 -| d |
------ ---
This can be used to emulate something similar to juxt
as follows:
var argsId = R.unapply(R.identity);
var juxt = R.converge(argsId);
var addSubtract10 = juxt([R.add(10), R.subtract(10)]);
addSubtract10(5); //=> [15, 5]
Alternatively (though perhaps less intuitive), R.commute can also be used over a list of functions. R.commute
takes a list of some applicative type and effectively turns it inside out to become an applicative of some list, where the applicative behaviour of functions now provided by Ramda is similar to converge
.
var juxt = R.commute(R.always);
var addSubtract10 = juxt([R.add(10), R.subtract(10)]);
addSubtract10(5); //=> [15, 5]
在某种程度上, R.ap
看起来像你想要的。
There is another fairly simple Ramda solution:
var juxt = R.useWith(R.ap, [R.identity, R.of]);
This was discussed in Ramda's issue #986 , but ended up being dropped when no one stepped up to champion the idea. Feel free to bring it back up.
从版本 v0.19.0 Ramda 添加并列
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.