Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ramda evolve function example

From Ramda Repl:

var tomato  = {firstName: '  Tomato ', data: {elapsed: 100, remaining: 1400}, id:123};

Why does this work:

var transformations = {
  firstName: ()=>'Potato'
};
// => {"data": {"elapsed": 100, "remaining": 1400}, "firstName": "Potato", "id": 123}

But this doesnt:

var transformations = {
  firstName:'Potato'
};
//=>{"data": {"elapsed": 100, "remaining": 1400}, "firstName": "  Tomato ", "id": 123}

R.evolve(transformations, tomato);

like image 950
KornholioBeavis Avatar asked Jun 09 '26 07:06

KornholioBeavis


1 Answers

R.evolve

Creates a new object by recursively evolving a shallow copy of object, according to the transformation functions. All non-primitive properties are copied by reference.

A transformation function will not be invoked if its corresponding key does not exist in the evolved object.

In short, the transformation must be a function.

Why does this work:

var transformations = {
  firstName: ()=>'Potato'
};

Because ()=>'Potato' is a function

But this doesnt:

var transformations = {
  firstName:'Potato'
};

Because 'Potato' is a string, not a function.

In such a case when the provided transformation is not a function, the original value.

Here's the source code for evolve. I bolded the code path your example takes to arrive at the output

module.exports = _curry2(function evolve(transformations, object) {
  var result = {};
  var transformation, key, type;
  for (key in object) {
    transformation = transformations[key];
    type = typeof transformation;
    result[key] = type === 'function'                 ? transformation(object[key])
                : transformation && type === 'object' ? evolve(transformation, object[key])
                                                      : object[key];
  }
  return result;
});
like image 158
Mulan Avatar answered Jun 11 '26 22:06

Mulan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!