Extending an object with Ramda

In notebook:
Work Notes
Created at:
2018-11-07
Updated:
2018-12-09
Tags:

Say you want to add a new property to an Object that is a result of some calculation of another property.

My first, perhaps naive attempt, with R.ap, apply:

  const mydata = {
    results: [1,2,3]
}

const getsum = R.compose(R.sum, R.prop('results'))
const addSum = R.ap(R.mergeDeepLeft, R.compose(R.objOf('sum'), getsum))
addSum(mydata) // => {results: [1, 2, 3], sum: 6}

Maybe it could be done more elegantly with R.assoc combined with R.lensProp

Another approach, this time extending a base object with calculated values representing the generated HTML and a path to write the file to:

  const somedata = {
      pants: 'shoes'
    }

const noteHTML = somedata => 'noteHTML'
const getPath = somedata => 'thepath'

const createFile = r => R.assoc('html', R.__, r)
const createPath = r => R.assoc('path', R.__, r)

const addHTML = R.ap(createFile, noteHTML)
const addPath = R.ap(createPath, getPath)

const createElem = R.compose(addHTML, addPath)

createElem(somedata) 

// =>
{
 pants: shoes,
 html: 'noteHTML',
 path: 'thepath'
}

and another way, by misusing the .ap applicative functor

  const somedata = { foo: 'bar' }

const calcNewProp = // will receive somedata and you return your new value

const ext = R.ap(
  R.compose(
    R.assoc('newprop'),
    calcNewProp
  ),
  R.identity
)

Then converted to a helper functtion:

  const calcProp = (p,f) => R.ap(
  R.compose(
    R.assoc(p),
    f
  ),
  R.identity
)
const calcPropR = R.curry(calcProp)

// usage
calcPropR('newprop', calcNewProp)(somedata)