joaquinlpereyra
joaquinlpereyra

Reputation: 966

Why isn't this recursion working on Javascript?

The problem is in the listToArray function, arrayToList just there to provide context on how lists are being created.

var arrayToList = function (array) {
    var lastList = null;
    for (i=array.length-1; i >= 0; i--) {
        var list = {value : array[i], rest : lastList};
        lastList = list;
    }
    return lastList;
}

var list = arrayToList([1,2,3])

var listToArray = function (list) {
    var array = [];
    array.push(list.value);
    if (list.rest != null) {
        array.concat(listToArray(list.rest));
    } else {
        return array;
    }
}

var array = listToArray(list)

> list
{ value: 1, rest: { value: 2, rest: { value: 3, rest: null } } }
> array
undefined

Upvotes: 0

Views: 68

Answers (1)

Ayan
Ayan

Reputation: 2380

Couple of fixes:

  • Have to return the array to be used in array.concat
  • Every time a new arr = [] loses the context of the previous. Either it should be passed as a parameter, or keeping it in a global context.

Run the following snippet.

var arrayToList = function(array) {
  var lastList = null;
  for (i = array.length - 1; i >= 0; i--) {
    var list = {
      value: array[i],
      rest: lastList
    };
    lastList = list;
  }
  return lastList;
}

var list = arrayToList([1, 2, 3])

var listToArray = function(list, array) {
  if (!array) {
    array = [];
  }
  array.push(list.value);
  if (list.rest != null) {
    array.concat(listToArray(list.rest, array));
  } else {
    return array;
  }
  // need to return the array which is used in array.concat
  return array;
}
var array = listToArray(list);
console.log(list);
console.log(array);

Upvotes: 1

Related Questions