0

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
2
  • 1
    There’s only a return statement in the else block, not in the if block. Commented Aug 4, 2016 at 1:42
  • Is this really something that could not be solved by stepping through your code in the debugge? Commented Aug 4, 2016 at 2:38

1 Answer 1

1

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);

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.