3

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?

1
  • Only objects are passed around as references, not values. Commented Feb 17, 2012 at 20:11

3 Answers 3

4

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()
Sign up to request clarification or add additional context in comments.

Comments

0

The problem is, as Ricardo Tomasi said, that you want to modify several values in-place. That necessitates either repeating yourself or, as Lucian suggests, using strings rather than identifiers.

What I'd recommend is storing your state in a more sophisticated structure than a simple object. If you put each value in its own object wrapper, e.g.

@au = {val: 5}

then you could simply write

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

You might in the future decide to store additional state in these objects. For instance, if you want to see what the random value was in the future, you could change the iterator to

  o.jitter = Math.random() * 0.1
  o.val *= (0.95 + o.jitter)

You might also want to think about using evented models (like those in Backbone.js) rather than simple objects.

Comments

0

I think I'd go about it like so:

thing = { a:1, b:2, c:3, d:4, e:5 }
for key, value of thing when key in ['a', 'c', 'd'] 
  thing[key] = value * 2

If I was going to mangle the same set of values in different ways very often, I'd probably split them out into their own collection as so:

thing = { stuff: { a:1, c:3, d:4 }, b:2, e:5 }
for key, value of thing.stuff 
  thing.stuff[key] = value * 2

That might make the intent clearer, and in functions that do a lot of stuff, it'd be only a minor imposition to make a local reference to it for brevity, i.e.:

doLotsOfStuff = (thing) ->
  stuff = thing.stuff
  stuff.a = 10
  stuff[key] = 1.0 / Math.pow(value,2) for key, value of stuff 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.