3

How can I call a function one's for multiple attributes ?

Something like:

fillTween (  
  option1.scale, 1; 
  option2.scale, 7; 
  option3.scale, 4; 
  option4.scale, 2; 
)

  function fillTween(attr, y) {
    var tween = new TWEEN.Tween(attr).to({
      y: y
    }, 1000);
    tween.easing(TWEEN.Easing.Elastic.InOut);
    tween.start();
  }

  $("input[name='radiogroup1']").change(function() {


    if ($('#radio1').is(":checked")) {


      fillTween(option1.scale, 1);
      fillTween(option2.scale, 7);
      fillTween(option3.scale, 4);
      fillTween(option4.scale, 2);

      ...

    }

  });
Robusto
  • 31,447
  • 8
  • 56
  • 77
Alexander Hein
  • 960
  • 3
  • 19
  • 44

2 Answers2

4

You can't. The solution there is just to rewrite the function to accept array of arguments.

function fillTween(attributes) {
  attributes.map(function(x) {
    var attr = x[0];
    var y = x[1];
    var tween = new TWEEN.Tween(attr).to({
      y: y
    }, 1000);
    tween.easing(TWEEN.Easing.Elastic.InOut);
    tween.start();
  })
}

And call it like this:

fillTween ([  
  [option1.scale, 1],
  [option2.scale, 7],
  [option3.scale, 4],
  [option4.scale, 2]
])
nicael
  • 18,550
  • 13
  • 57
  • 90
  • Since you are not using the returned array of the `map` function and there are no other side-effects on the input array, this should probably be replaced with `forEach`? – kuhnroyal Jan 17 '16 at 15:01
  • @kuhn I don't get it? Why do I need to return the array? – nicael Jan 17 '16 at 15:03
  • @kuhn If you've misunderstood something: I'm using the map here just to iterate, and I don't need the returned value. – nicael Jan 17 '16 at 15:05
  • I know, you don't need it. But `map` is still creating a new array which you just throw away. `forEach` operates on the input array. http://stackoverflow.com/questions/7340893/what-is-the-difference-between-map-every-and-foreach – kuhnroyal Jan 17 '16 at 15:06
  • @kuhn I'm absolutely aware of that. Do you feel sorry for the array being thrown away? If not, then there's still no point to suggest `forEach`. `map` is just shorter. – nicael Jan 17 '16 at 15:09
  • Just basic performance, granted it doesn't really matter with an array of this size, but still `forEach` is faster then `map`. – kuhnroyal Jan 17 '16 at 15:16
3

If you don't wish to modify your function and/or potentially want to do a similar thing for different functions, you can modify the Function prototype to create a new "multiple" function like this:

Function.prototype.multiple = function() {
  for (var i = 1; i < arguments.length; i++) {
    this.apply(arguments[0],arguments[i]);
  }
}

Then you can call the function multiple times with the following:

fillTween.multiple(this,
  [ option1.scale, 1 ], 
  [ option2.scale, 7 ],
  [ option3.scale, 4 ],
  [ option4.scale, 2 ] 
);
Justin Heath
  • 401
  • 2
  • 7