简体   繁体   中英

How i can compose that function with ramda?

How i can create addGreeting function in ramda way?

I try to create a function, but it think it is not best solution.

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);

I expect to write addGreeting function with ramda.


UPD: my solution

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({});

You can use R.curry to create addGreeting and R.applySpec to create the animal creation function:

 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>

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