0

I am writing a function to convert array to List using Javascript.

If the input array is as below:

let inputArray = [1,2,3]

The output object should be like the below:

let outputList = { 
    value: 1, 
    rest: {
        value: 2,
        rest: {
            value : 3,
            rest: null } } }

I have the below function that accepts a nested object as its parameter and returns a string that represents where in the object, the property is null:

function getLastValue(object) {
   let s = '';
   if (object.rest) {
     return s += '[rest]' + getLastValue(object.rest);
   } else {
     return s;
}

And the below function that converts an array to a list:

var list = {value: '', rest: null};

function constructList(arr) {
    for (let prop of arr) {
        let lastValue = getLastValue(list);
        `${list}${lastValue}`.value = prop;
        `${list}${lastValue}`.rest = null;
    }
    return list;
}

The constructList function fails to work as ${list}${lastValue} is a string. I need to convert the above from

'list[rest][rest]' 

to

list[rest][rest]

Any help is appreciated!

inuYasha
  • 11
  • 4

1 Answers1

1

This would be a great place to use reduceRight - construct the innermost object first, and have it be the new value of the accumulator, which is assigned to the next innermost object's rest property, and so on:

const constructList = arr => arr.reduceRight(
  (rest, value) => ({ value, rest }),
  null
);
console.log(
  constructList([1, 2, 3])
);

To fix your original code, rather than constructing a string that attempts to refer to the nested object, iterate through the nested structure to find the innermost rest property instead, and return the object that doesn't contain a truthy rest property:

function getLastValue(obj) {
  while (true) {
    if (!obj.rest) return obj;
    obj = obj.rest;
  }
}

var list = {
  value: '',
  rest: null
};

function constructList(arr) {
  for (let prop of arr) {
    const nestedObj = getLastValue(list);
    nestedObj.value = prop;
    nestedObj.rest = {};
  }
  getLastValue(list).rest = null;
  return list;
}

console.log(
  constructList([1, 2, 3])
);
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320