wahoowa wahoowa - 23 days ago 6
Javascript Question

Nested list to array

I'm struggling with this kata that instructs me to create an array from a nested listed. I can find explanations for how to do this using Java but that's still a bit confusing for me.

This is what I've got so far...



function listToArray(list) {
var listArray = [];
for (var i = 0; i < list.length; i++) {
listArray[i] = list.value(i);
};
return listArray;
};





The test cases...



var list1 = {value: 1, next: {value: 2, next: {value: 3, next: null}}};
var list2 = {value: "foo", next: {value: "bar", next: null}};

Test.assertSimilar(listToArray(list1), [1, 2, 3]);
Test.assertSimilar(listToArray(list2), ["foo", "bar"]);





Thanks for the help!

Answer

This is simply a linked list pointer chase:

function listToArray(list) {
  var listArray = [];
  while (list !== null) {
    listArray.push(list.value);
    list = list.next;
  }
  return listArray;
};