Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript / Coffeescript: how to run a function on many variables (and modify them) elegantly?

I will write Coffeescript but the javacript generated should e evident I want to run a function on many variables and I want to keep the result on them, as they are properties of the object that are read somewhere else. As it seems that Javascript will put them as value and not reference, I have only found this ugly way to implement what I want:

[@au, @iu, @rdis, @rtres, @rmin, @rmax, @dmil, @dal, @dacc] =
    [@au, @iu, @rdis, @rtres, @rmin, @rmax, @dmil, @dal, @dacc].map (x) -> x * (0.95 + Math.random()*0.1)

There is no better way of doing this?

like image 326
user1216071 Avatar asked Dec 29 '25 11:12

user1216071


1 Answers

One way might be:

for i in ['au', 'iu', ...]
  this[i] *= 0.95 + Math.random() * 0.1

Alternatively, you could instead compose an object of those values into your class:

getRands = ->
  dict = {}
  for i in ['au', 'iu', ...]
    dict[i] *= 0.95 + Math.random() * 0.1

@vars = getRands()
like image 62
Lucian Avatar answered Jan 01 '26 03:01

Lucian



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!