R
R
Ruslan Timurziev2017-11-07 20:36:11
JavaScript
Ruslan Timurziev, 2017-11-07 20:36:11

How to solve the problem in tree traversal (does not store value)?

function queryString(obj, nodePath, hist) {
  nodePath = nodePath || '';
  hist = hist || '';
  Object.keys(obj).forEach(k => {
    if (typeof obj[k] == 'object' && obj[k] !== null) {
      // console.log('obj', k);
      nodePath += '{}==' + k;
      queryString(obj[k], nodePath, hist);    
    } else {
      hist += nodePath;
      hist += '{}!=' + k;
    }
  });
  return hist;
}

Structure for example:
{
  a: {
    b: {
      c: {
        e: 'hello'
      },
      d: 'aloha'
    }
  }
}


The queryString function is a recursion that traverses the tree and creates a string. The obj parameter takes the structure above. The function should return a hist argument, which is intended to look like this:
'{}==a{}==b{}==c{}!=e' + '{}==a{}==b{}!=d' // разделил для удобочитаемости

nodePath is only needed to remember object/branches paths.
So here's the question:
On the first hit of else, hist should equal '{}==a{}==b{}==c{}!=e' (if you output hist at this point, then it is). However, when we iterate further through the loop and hit the if - hist is already empty.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Rsa97, 2017-11-07
@RuslanTimuziyev

So you don't use the hist value returned by the queryString function anywhere in the recursion.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question