spaceDog spaceDog - 6 months ago 20
Javascript Question

Javascript Recursion?

I am practicing recursion. Conceptually I understand how this should work, (see below) but my code isn't working.

Please tell me what I am doing wrong., and please please explain each step why your code works. Clear Explanation is ten times better than just giving me a code that works.

/*
buildList(0, 5) == buildList(0, 5 - 1) // [0]
buildList(0, 4) == buildList(0, 4 - 1) // [0,0]
buildList(0, 3) == buildList(0, 3 - 1) // [0,0,0]
buildList(0, 2) == buildList(0, 2 - 1) // [0,0,0,0]
buildList(0, 1) == buildList(0, 1 - 1) // [0,0,0,0,0]
*/

var buildList = function(value, length) {
var result = [];
if (length === 0) {
return result;
}

result.push(value);

return buildList(result.push(value), length - 1);

};


buildList(0, 5);


I understand how the recursion works on conceptual level.

Answer

Your approach can't work, because the base case returns a new empty array, and other cases return the result of the recursion.

Instead, you should first recurse and then push

var buildList = function(value, length) {
  if (length <= 0) return [];
  var recur = buildList(value, length-1);
  recur.push(value);
  return recur;
};

Alternatively, in the base case you can avoid creating a new array

var buildList = function(value, length, array=[]) {
  if (length <= 0) return array;
  array.push(value);
  return buildList(value, length-1, array);
};
Comments