Ramda帮助:Pointfree实现w /占位符直接参数

时间:2015-10-17 22:41:37

标签: javascript functional-programming currying ramda.js

这是我第一次使用ramda。我试图创建一个地图函数,自动在数组中为每个对象添加一个键。对无状态函数有帮助,例如,我们可能有一个带签名的函数

 ({ prop1, prop2, key }) => ...

的数组
 [{ prop1: 'prop one', prop2: 'prop two' }, {...etc}]

这是一个有效的例子:

const mapI = R.addIndex(R.map);
const mapAddIndexedProp = R.curry((key, fn) => mapI(R.pipe(R.flip(R.assoc(key)), fn)));
const mapAddKeyProp = mapAddIndexedProp('key');

但是,看到我真正想要的是一个接受字符串和函数的函数,似乎应该有办法做一些事情:

const mapAddIndexedProp = mapI(R.pipe(R.flip(R.assoc(<arg1>)), <arg2>));

但我无法弄清楚它是如何运作的。任何想法都将不胜感激。

或者,极有可能的是,通过&#34; over&#34;或转换。谢谢!

1 个答案:

答案 0 :(得分:2)

我认为如果你不努力让它无分数,这是非常简单的:

const addKey = R.curry((key, fn, vals) => 
    R.map(obj => 
        R.assoc(key, fn(obj), obj), vals));

如果您确实也想要索引,可以将其扩展为:

const addKey2 = R.curry((key, fn, vals) => 
    R.addIndex(R.map)((obj, idx) => 
        R.assoc(key, fn(obj, idx), obj), vals));

你可以使用就像这样:

const addFullNames = addKey('fullName', person => 
    `${person.first} ${person.last}`
);

const initials = person => R.head(person.first) + R.head(person.last);
const  addIds = addKey2('id', (person, idx) => `${initials(person)}_${idx}`)

var people = [
    {first: 'Wilma', last: 'Flintstone'}, 
    {first: 'Betty', last: 'Rubble'}
];

addFullNames(people); //=>
// [
//     {first: 'Wilma', last: 'Flintstone', fullName: 'Wilma Flintstone'}, 
//     {first: 'Betty', last: 'Rubble', fullName: 'Betty Rubble'}
// ];

addIds(people); //=>
// [
//     {first: 'Wilma', last: 'Flintstone', id: 'WF_0'}, 
//     {first: 'Betty', last: 'Rubble', id: 'BR_1'}
// ];

我确信有一种方法可以让这一点免费。但是我也很确定它看起来会更不优雅。