Yellowfun
Yellowfun

Reputation: 558

Is it possible to implement arrayToList function in JS not from stepping through the array backwards?

function arrayToList(array) {
  var list = null;
  for (var i = array.length - 1; i >= 0; i--) //How to implement it if i = 0?
    list = {
      value: array[i],
      rest: list
    };
  return list;
}

arr.reverse - not offer. I'm curious how it can be done if we're stepping through the array from array[0]? Or this task in JS only can be done if we're stepping through the array backwards?

Upvotes: 1

Views: 64

Answers (3)

georg
georg

Reputation: 215019

The trick is to use two separate pointers for the list head and for the current node:

function arrayToList(a) {
    var list = {}, p = list;
    for (let x of a) {
        p.value = x;
        p.rest = {};
        p = p.rest;
    }
    return list;
}


console.log(arrayToList([11,22,33]))

To nullify the last pointer you're going to need three pointers:

function arrayToList(a) {
    var list = {}, p = list, q;
    for (let x of a) {
        p.value = x;
        p.rest = {};
        q = p;
        p = p.rest;
    }
    q.rest = null;
    return list;
}

Upvotes: 1

synthet1c
synthet1c

Reputation: 6282

You could do it without a loop, using recursion instead.

function arrayToListRecursive(arr) {
  return (!arr.length)
    ? null
    : {
        value: arr[0],
        rest: arrayToListRecursive(arr.slice(1))
      }
}


function arrayToListLoop(arr) {
  let list = null;
  for (let i = 1; i <= arr.length; i++) {
    list = { value: arr[arr.length - i], rest: list };
  }
  return list
}

console.log(
  arrayToListRecursive([1, 2, 3, 4])
)

console.log(
  arrayToListLoop([1, 2, 3, 4])
)
<script src="https://codepen.io/synthet1c/pen/KyQQmL.js"></script>

Upvotes: 1

Nina Scholz
Nina Scholz

Reputation: 386726

You could reduce an object and assign at the end null.

function arrayToList(array) {
    var list = {};
    array.reduce((o, v, i, a) => (o.value = v, o.rest = i + 1 === a.length ? null : {}), list);
    return list;
}

console.log(arrayToList([4, 5, 6, 7]));
.as-console-wrapper { max-height: 100% !important; top: 0; }

Upvotes: 1

Related Questions