我怎样才能用ramda组成该功能?

时间:2019-03-28 13:11:52

标签: javascript functional-programming ramda.js

我如何以ramda方式创建addGreeting函数?

我尝试创建一个函数,但它不是最佳解决方案。

const animal = {};

const addName = R.assoc('name');

const addGreeting = (transformString) => (animal) => {
  return R.assoc('greeting', transformString(animal), animal);
};

const createAnimal = 
 R.pipe(
   addName('Igor'),
   addGreeting(animal => `Hello ${animal.name}`),
 );

createAnimal(animal);

我希望用ramda编写addGreeting函数。


UPD:我的解决方案

const addName = R.assoc('name');

const addGreeting = 
  (transformString) => 
    R.converge(
      R.merge,
      [
        R.applySpec({
          greeting: transformString
        }),
        R.defaultTo({})
      ]
    )

const createAnimal = 
 R.pipe(
   addName('Igor'),
   addGreeting(animal => `Hello ${animal.name}`),
 );

createAnimal({});

1 个答案:

答案 0 :(得分:1)

您可以使用R.curry创建addGreetingR.applySpec创建动物创建功能:

const { curry, applySpec, identity } = R

const addGreeting = curry((transformString, name) => transformString(name));

const createAnimal = applySpec({
  name: identity,
  greeting: addGreeting(name => `Hello ${name}`)
})

console.log(createAnimal('Igor'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.26.1/ramda.js"></script>