Sterzhakov
Sterzhakov

Reputation: 25

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

Upvotes: 1

Views: 60

Answers (1)

Ori Drori
Ori Drori

Reputation: 193057

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>

Upvotes: 1

Related Questions