简体   繁体   中英

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

tl;dr : I'm looking for Ramda's ( http://ramdajs.com ) equivalent of Mori's knit function.

I want to apply a different function to the key and value in a key/value pair. This (contrived) example uses mori.knit(f0, f1, ...) to apply the toUpper function on the key and the toLower function on the value of a key/value pair:

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

I'm looking for the equivalent using Ramda to apply a different function to the key and value of a key/value pair.

Ramda does not have precisely that function. It's not hard to build something close. Here's a version that is similar, with a slightly altered API and more generality:

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]]

If you really want to pass the list in the initial call, you could write it like this:

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

And if that version seems needlessly cryptic, you could always use a version that isn't points-free such as:

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

But none of these has a free list of functions; they're wrapped in a list. That is the norm for Ramda functions. If you really want one more like the mori function, your could add an unapply :

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

My personal preference would be for the simplest one:

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

You can play with some of these variants on the Ramda REPL .

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.

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