-1
var data = {
   "factors" : [1,2,34]
}

I would like to multiply all the elements in the factors array by 2 using ramda JavaScript and return the updated data object.

Xantium
  • 11,201
  • 10
  • 62
  • 89
Anamika
  • 21
  • 4
  • And what have you tried so far? – Scott Sauyet Feb 16 '18 at 22:03
  • const attributeLens = R.lens(R.prop(propertyName),.assoc(propertyName)); var attributeConversionLens = R.over(attributeLens, R.multiply(conversionFactor));return R.compose(attributeConversionLens); – Anamika Feb 16 '18 at 22:50

1 Answers1

0

It looks like your attempts are moving in the right direction. It would help if you edited your question to show what you've tried, rather than only including it in the comments.

There are of course many ways you can do this.

The simplest one might be this, which hard-codes your 2 and factors:

const {over, lensProp, map, multiply} = R

const multFactors = over(lensProp('factors'), map(multiply(2)))

console.log(multFactors({"factors" : [1,2,34]}))
<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.js"></script>

But if you want those passed in, then something like this might be better:

const {over, lensProp, map, multiply} = R

const multAllBy = (propName, multiplier, data) => 
    over(lensProp(propName), map(multiply(multiplier)), data)

console.log(multAllBy('factors', 2, {"factors" : [1,2,34]}))
<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.js"></script>

Note the position of data: it is the last parameter to the function, and it's used only in the last position of the call. In that case, we can create a closer-to-curried version simply by removing the parameter. But note the way that we have to call it now. That's fine if you're reusing the intermediate function. If not, this approach gains you nothing.

const {over, lensProp, map, multiply} = R

const multEachBy = (propName, multiplier) => over(
    lensProp(propName), 
    map(multiply(multiplier))
)

console.log(multEachBy('factors', 2)({"factors" : [1,2,34]}))
<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.js"></script>

None of those are point-free. If you're trying to get a point-free solution or one that what is fully curried the Ramda way (which you could also get by wrapping curry around one of the last two), then this might be more to your liking:

const {over, lensProp, map, multiply, useWith, compose, identity} = R

const multEverythingBy = useWith(over, [lensProp, compose(map, multiply), identity])

console.log(multEverythingBy('factors', 2, {"factors" : [1,2,34]}))
<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.js"></script>
Scott Sauyet
  • 49,207
  • 4
  • 49
  • 103