2
var rockPaperScissors = function(rounds) {
  var outcomes = [];
  var plays = ['rock', 'paper', 'scissors'];
  var playedSoFar = [];

  var combos = function(roundsToGo) {
    // base case
    if (roundsToGo === 0) {
      outcomes.push(playedSoFar.slice());
      return;
    }

    for (var i = 0; i < plays.length; i++) {
      playedSoFar.push(plays[i]);
      combos(roundsToGo - 1);
      playedSoFar.pop();
    }
  };
  combos(rounds);
  return outcomes;
};

console.log(rockPaperScissors(2));

If I take out the slice() from the playedSoFar, outcomes just gets returned as nine empty arrays, instead of all the combinations from a 2 round rock paper scissors game:

[ [ 'rock', 'rock' ],
  [ 'rock', 'paper' ],
  [ 'rock', 'scissors' ],
  [ 'paper', 'rock' ],
  [ 'paper', 'paper' ],
  [ 'paper', 'scissors' ],
  [ 'scissors', 'rock' ],
  [ 'scissors', 'paper' ],
  [ 'scissors', 'scissors' ] ]

Why doesn't this work when I take out the slice() from the playedSoFar?

Lucian
  • 644
  • 3
  • 13
WinchenzoMagnifico
  • 3,075
  • 5
  • 20
  • 23

2 Answers2

1

.slice() returns a copy of your array, if you don't use .slice() and just push the playedSoFar array then its updated contents will be reflected throughout the scope, therefore they will be reflected in the combos array. More details here.

Community
  • 1
  • 1
Lucian
  • 644
  • 3
  • 13
  • thanks this was a lot more helpful – WinchenzoMagnifico Aug 01 '15 at 20:27
  • No problem. At first, I didn't quite understand what the question was. There are more questions like 'JavaScript pass by reference vs. pass by value' throughout SO if you really want to understand how JavaScript works under the hood. – Lucian Aug 01 '15 at 20:29
1

If you want to retain playedSoFar, then this is the way to go:

  outcomes=outcomes.concat(playedSoFar);
EugenSunic
  • 13,162
  • 13
  • 64
  • 86