wahoowa
wahoowa

Reputation: 45

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!

Upvotes: 0

Views: 126

Answers (4)

Gavin
Gavin

Reputation: 4515

You just have to dig deeper into the object until you reach the null point.

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

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

console.log(listToArray(list1));
console.log(listToArray(list2));

Upvotes: 1

Pranav C Balan
Pranav C Balan

Reputation: 115282

Do it with recursion

function listToArray(list) {
  var res = [];
  Object.keys(list).forEach(function(k) {
    if (typeof list[k] == 'object' && list[k] !== null)
      [].push.apply(res, listToArray(list[k]));
    else if (list[k] !== null)
      res.push(list[k]);
  });
  return res;
};

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

console.log(listToArray(list1));
console.log(listToArray(list2));

Upvotes: 1

kukkuz
kukkuz

Reputation: 42380

Another solution using recursion:

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

function convertToArray(list, result) {
  result.push(list.value);
  list.next && convertToArray(list.next,result);
  return result;
}

console.log(convertToArray(list1,[]));
console.log(convertToArray(list2,[]));

Upvotes: 1

Dan D.
Dan D.

Reputation: 74685

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

Upvotes: 4

Related Questions