[알고리즘][js]Tree map method

김_리트리버·2020년 8월 3일
0

[알고리즘]

목록 보기
1/47

var Tree = function (value) {
  this.value = value;
  this.children = [];
};

Tree.prototype.map = function (callback) {

  /* 
  
  *  newTree.value // 2

  *  newTree.children[0].value // 4
  *  newTree.children[1].value // 6
  * 
  *  newTree.children[0].children[1].value // 10
  *  newTree.children[1].children[1].value // 14
  * 
  */
 
  //  => 반복되는 것 : 원본tree 자식의 value 를 callback 처리한다. 
  // callback 처리된 값으로 새로운 tree instance 를 생성한다. 
  // 리턴할 새로운 Tree 에 붙인다. 

  let newTree = new Tree(callback(this.value));


  function makeNewChildRecursive(originTree, newTree) {

    if (originTree.children.length < 1) {
      // 기준이 되는 원본tree 의 자식이 없으면 반복하지 않는다. 
      return;
    }

    for (let originChild of originTree.children) {
	// 원본트리의 자식 수 만큼
      // 원본트리 자식의 value 를 callback 처리한 것으로 
      // 새로운 tree instance 를 생성 
      // 리턴할 전체 tree 에 붙인다. 
      let newChild = new Tree(callback(originChild.value));
      newTree.addChild(newChild);
	// 자식의 자식이 있을 경우 반복 
      makeNewChildRecursive(originChild, newChild);
    }
  }

  makeNewChildRecursive(this, newTree)

  return newTree;

};

Tree.prototype.mapInPlace = function (callback) {

  // 자기 자신의 value 를 callback 처리한것으로 변경 
  this.value = callback(this.value);

  function changeChildRecursive(tree) {
// 자식이 없으면 반복하지 않음 
    if (tree.children.length < 1) {
      return;
    }
// 자식 수 만큼 callback 처리한 것으로 value 변경
    for (let child of tree.children) {

      child.value = callback(child.value);
// 자식의 자식이 있을 경우 반복 
      changeChildRecursive(child);
    }

  }

  changeChildRecursive(this)
  return this;
  //update the values of the existing tree with values generated by the callback
};


Tree.prototype.addChild = function (child) {

    child = new Tree(child);
    this.children.push(child);

  return child;
};

profile
web-developer

0개의 댓글