Saturday 18 March 2017

How to find the roots of several trees within one object

I have a series of messages which contain unique numerical IDs, unique IDs and non-unique "in reply to" fields that reference other messages. From this object, I'm trying to find the roots of all of the trees, as well as all of the children corresponding to those trees. I've found it relatively easy to return an object containing a series of nodes with their corresponding children, but I'm having trouble merging them in an efficient way. Unfortunately, this tree could be thousands of levels deep, or just one level which makes the task considerably harder.

let exampleTree = {
  1: {
    'ID': 'IDONE',
    'IN_REPLY_TO': undefined    
  },
  3: {
    'ID': 'IDTHREE',
    'IN_REPLY_TO': 'IDONE'
  },
  7: {
    'ID': 'IDSEVEN',
    'IN_REPLY_TO': 'IDTHREE'
  },
  8: {
    'ID': 'IDEIGHT',
    'IN_REPLY_TO': 'IDTHREE'
  }
}

// should return { 1: [3, 7, 8] }

function generateMap(tree) {
  let convert = {}
  let mapped = {}
  for (let id in tree) {
    if (typeof tree[id].IN_REPLY_TO != 'undefined') {
      if (typeof mapped[tree[id].IN_REPLY_TO] != 'undefined') {
        mapped[tree[id].IN_REPLY_TO].push(tree[id].ID)
      } else {
        mapped[tree[id].IN_REPLY_TO] = [tree[id].ID]
      }
    }
    convert[tree[id].ID] = id
  }
  let uidMapped = {}
  for (let id in mapped) {
    uidMapped[convert[id]] = mapped[id].map(function(value) { return convert[value] })
  }
  return uidMapped
}

console.log(generateMap(exampleTree))

// currently returns { 1: [3], 3: [7, 8] }

Hopefully, the example above makes it clear what I'm trying to accomplish. Seven and eight are both children of three, which in turn is a child of one. I'm trying to combine these two together.



via Popey Gilbert

No comments:

Post a Comment