0

I'm working on getting started with JavaScript. I implemented a simple function to convert an array to a singly linked list, and then iterate over it recursively to return the value at a particular position. My code currently logs undefined for all position values except 0. What causes it to behave this way?

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

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

function nth(list, count) {
  if (!list) return undefined;
  if (count == 0) return list.value;
  else nth(list.rest, count - 1);
}

console.log(nth(list,2));

2 Answers 2

1

The problem is that the "else" clause in the nth function does not return a value, so undefined is returned by default.

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

Comments

0

Look at my example over here

https://github.com/aloksguha/smartll

or you can try it out as node library. "smart-ll".

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.