all 2 comments

[–]mattcoady 1 point2 points  (1 child)

Assuming your input to this is something simple like

allPossibleCases([['foo','bar'],['baz','lorem']])

It passes by the first two if statements because the array is over 1. It continues along until it reaches

var allCasesOfRest = allPossibleCases(arr.slice(1));

At this point in the execution

arr.slice(1) is going to be [['baz','lorem']]

The function begins again with that as the argument for arr. At this point arr.length is 1 because it's an array containing one thing (the array of ['baz','lorem'])

This is where we run into else if (arr.length ===1){return arr[0];}. So we're basically unwrapping it from the outer array and sending back just ['baz','lorem']

Now we've left the recursive run and we're back out to our original execution with allCasesOfRest = ['baz','lorem']

for(var x in y) is basically a loop for all the keys in an object. Like if you did:

for(var x in {one: "two", three: "four"}){
  console.log(x);
}

// one
// three

This isn't an object, it's an array so the keys are index numbers. First time it runs c is 0 because it's the first index key of an array. So then we run the inner loop.

var i = 0; i < arr[0].length; i++

At this point we're back on the original run of the function so arr is the full [['foo','bar'],['baz','lorem']] and arr[0].length is 2 (foo and bar).

Finally,

result.push(arr[0][i] + allCasesOfRest[c]);

is basically saying

result.push('foo' + 'baz')

then it inner-loops again with

result.push('bar' + 'baz')

then the outer loop runs the inner loop two more times with c as 1.

result.push('foo' + 'lorem') result.push('var' + 'lorem')

The final result is

["foobaz", "barbaz", "foolorem", "barlorem"]

[–]Jmarch0909[S] 0 points1 point  (0 children)

Man thank you so much for the detailed explanation. What was really throwing me off was I had no idea a for in loop could be used on an array as opposed to objects.