Home > Net >  How to perform 2 functions one after the other with forEach, without looping twice?
How to perform 2 functions one after the other with forEach, without looping twice?

Time:11-28

Does anyone know how can I do the same thing as that :

Player.list.forEach(player => {
    player.firstLayer();
});

Player.list.forEach(player => {
    player.secondLayer();
});

But looping it only one time to make it faster.

(I want to execute all firstLayer function of all players, and then execute secondLayer function, but without looping it Player.list two times)

Thanks for answer.

CodePudding user response:

This is not possible and there is no real difference in performance. The Big O notation is a mathematical notation that describes the limiting behavior of a function when the argument tends towards a particular value or infinity. There is no difference between running over the loop once or twice. The difference of O(n) vs O(2n) in terms of asymptotic complexity doesn't exist since both have the "linear" growth rate.

CodePudding user response:

The only thing you can do is

Player.list.forEach(player => {
  player.firstLayer();
  player.secondLayer();
});

but this will execute directly the second layer immediately after the first layer for each element. If the second layer for every element is different you cannot do what you want without looping again.

  • Related