繁体   English   中英

使用Ramda将不同的功能应用于一对的键和值

[英]Apply different function to key and value of a pair using Ramda

tl; dr :我正在寻找与Mori的knit函数等效的Ramda( http://ramdajs.com )。

我想对键/值对中的键和值应用不同的功能。 这个(人为的)示例使用mori.knit(f0, f1, ...)toUpper函数应用于键,并将toLower函数应用于键/值对的值:

const pairs = [ [ "key1", "VAL1" ], [ "key2", "VAL2" ], ... ]);
const result = mori.knit(toUpper, toLower, pairs);
// => [ [ "KEY1", "val1" ], [ "KEY2", "val2" ], ... ]

我正在寻找使用Ramda的等效项,以将不同的功能应用于键/值对的键和值。

Ramda并没有该功能。 建立紧密的关系并不难。 这是一个相似的版本,API稍有变化,通用性更高:

const knit = compose(map, zipWith(call));

const pairs = [["key1", "VAL1"], ["key2", "VAL2"], ["key3", "VAL3"]];
knit([toUpper, toLower])(pairs);
//=> [["KEY1", "val1"], ["KEY2", "val2"], ["KEY3", "val3"]]

const triples = [["key1", "VAL1", 1], ["key2", "VAL2", 2], ["key3", "VAL3", 3]];
const square = n => n * n;
knit([toUpper, toLower, square])(triples);
//=> [["KEY1", "val1", 1], ["KEY2", "val2", 4], ["KEY3", "val3", 9]]

如果您真的想在初始调用中传递列表,则可以这样编写:

const knit = useWith(map, [zipWith(call), identity]);

而且,如果该版本看起来似乎是不必要的神秘性,则可以始终使用并非没有分数的版本,例如:

const knit = (fns, xs) => map(zipWith(call, fns), xs);

但是这些都没有免费的功能列表。 它们包装在列表中。 那是Ramda函数的规范。 如果你真的想要一个更喜欢的家蚕功能,您可以添加一个unapply

const knit = compose(map, unapply(zipWith(call)));
knit(toUpper, toLower)(pairs);
knit(toUpper, toLower, square)(triples);

我个人最喜欢的是最简单的一个:

const knit = compose(map, zipWith(call));
knit([toUpper, toLower])(pairs);
knit([toUpper, toLower, square])(triples);

您可以在Ramda REPL上使用其中一些变体。

暂无
暂无

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

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