Search code examples
javascriptfunctional-programmingramda.jsfolktale

How to apply properties of an object to functions?


I want to apply different functions to some object properties. Lets say I have this object:

const person = {
  name: 'John',
  age: 30,
  friends: [],
};

and i have some functions that i want to apply to those properties:

const upperCase = str => str.toUpperCase() //for the name

const add10 = int => int + 10 // for the age

const addFriend = (value,list) => [...list,value] // adding a friend

and this should be the result:

const person = {
  name: 'JOHN',
  age: 40,
  friends: ['Lucas']
}

What is the best way to achieve this using functional programming and point free, and if you could include examples using Ramda I would appreciate it, Thanks!


Solution

  • With Ramda, you're looking at the evolve function:

    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.

    You probably need to define "transform" functions on the fly; I bet you don't want to add 'Lucas' as a friend of every single person. Hopefully this is enough to get you started.

    const transform =
      evolve(
        { name: toUpper
        , age: add(10)
        , friends: prepend('Lucas')
        });
        
        
    console.log(
    
      transform(person)
    
    );
    <script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.26.1/ramda.min.js"></script>
    <script>const {evolve, toUpper, add, prepend} = R;</script>
    <script>
    const person =
      { name: 'John'
      , age: 30
      , friends: []
      };
    </script>


    Point-free style is not the only way

    ⚠️

    Please note that I've been able to implement this point-free style because I could hardcode each transformation functions. If you need to craft a transformation object on the fly, doing so point-free style is likely to be unreadable quickly.