Search code examples
javascriptfunctional-programmingmonadsramda.jsramda-fantasy

How to execute a function that returns a function inside of IO monad


I am using "Ramda/Fantasy" library for creating Monads. And i am trying to combine IO's to get element from the DOM and change its text content. But the problem is that function that changes content of the element needs to take two arguments element, and text that we want to set. I don't know how I can that efficiently I found one solution that looks like this:

const getElement = id => IO(() => document.querySelector(id));
const setElementText = element => text => IO(() => element.textcontent = text);

getElement('h1').map(setElementText).runIO()('New Title').runIO();

Is there a better way?


Solution

  • Two small changes to help with your example:

    • Swapping the order of the arguments to setElementText allows you to partially apply the text value.
    • Using chain rather than map remove the need for the second runIO call.
    const getElement = id => IO(() => document.querySelector(id))
    const setElementText = text => element => IO(() => element.textContent = text)
    
    getElement('h1').chain(setElementText('New Title')).runIO()