Lucky Lucky - 4 months ago 10
Javascript Question

Object.keys in reverse order

I have interesting task. I solved the half of it but can't to find the solution to solve the rest. Hope someone can point me to the right direction.

I found the solution close to mine task. But mine is slightly different and use ES6.

There is nested object.

let someList = {

value: 1,

next: {

value: 2,

next: {

value: 3,

next: {

value: 4,

next: null

}

}

}

};


I received all values.

function reversePrint(linkedList) {

Object.keys(linkedList).map(key => {
let myKey = linkedList[key];
typeof myKey == "object" ? console.log(reversePrint(myKey)) : console.log(myKey);
});

}

reversePrint(someList);


But the problem is: how i can get all values in reverse order?

Fiddle: https://jsfiddle.net/L83puqbz/17/

I tried use reduce for to make array and reverse it but every value was in separate array.

Fiddle https://jsfiddle.net/L83puqbz/20/

Any help will be greatly appriciated.

Answer

EDIT - sorry yes, more explanation.

The following code will go through the linked list and print the values in reverse order.

Since the log is after the recursive call, this will go all the way to the last node before the console logs start. Then, when it reaches the console.log it will print the latest node, then that function will finish allowing the next function on the stack to continue.

let someList = {
  value: 1,
  next: {
    value: 2,
    next: {
      value: 3,
      next: {
        value: 4,
        next: null
      }
    }
  }
};

function printAfter(node){
  if(node.next != null){
    printAfter(node.next);
  }
  console.log(node.value);
}

printAfter(someList)