简体   繁体   English

JavaScript/Ramda 中的等效函数作为 Clojure 的 juxt

[英]Equivalent function in JavaScript/Ramda as Clojure's juxt

I need the functionality of Clojure's juxt function in JavaScript.我需要 JavaScript 中 Clojure 的juxt函数的功能。 Is there a native function for this?是否有本机功能? We're using the Ramda functional JavaScript library .我们正在使用Ramda 函数式 JavaScript 库 Is there a Ramda function with the juxt functionality?是否有具有juxt功能的juxt函数?

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: R.converge ,在使用每个函数的结果作为作为converge的第一个参数提供的函数的相应参数位置之前,它通过提供列表中的每个函数管道给定值 - 也许用图表更好地解释:

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:这可用于模拟类似于juxt ,如下所示:

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也可以用于一系列函数。 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 . R.commute接受一些 applicative 类型的列表,并有效地将它翻过来成为某个列表的 applicative,其中R.commute现在提供的函数的 applicative 行为类似于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:还有另一个相当简单的 Ramda 解决方案:

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.这在 Ramda 的issue #986 中进行了讨论,但是当没有人站出来支持这个想法时,最终被放弃了。 Feel free to bring it back up.随意把它拿回来。

从版本 v0.19.0 Ramda 添加并列

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM