Immersive #1 self Assignment

TheJang·2020년 3월 29일
0

immsersive 첫번째 퀴즈 다소 난이도는 낮았지만 푸는데 있어서 map함수의 기능과 재귀의 사용에 대해 재고하게 되는 문제였다.

Tree의 addchild와 map함수를 작성하는 문제

<내 풀이>


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

Tree.prototype.addChild = function(value) {
  let childNode = new Tree(value);
  this.children.push(childNode);
};

Tree.prototype.map = function(callback) {
  let node = new Tree();
  node.value = callback(this.value);

  if (this.children) {
    for (let i = 0; i < this.children.length; i++) {
      node.children[i] = this.children[i].map(callback);
    }
  }
  return node;
};

module.exports = Tree;

< 레퍼런스 풀이 >

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

Tree.prototype.addChild = function(child) {
  if (!child || !(child instanceof Tree)) {
    child = new Tree(child);
  }
  this.children.push(child);
  // return the tree for convenience
  return this;
};

Tree.prototype.map = function(callback) {
  return this.children.reduce(function(tree, child) {
    return tree.addChild(child.map(callback));
  }, new Tree(callback(this.value)));
};

module.exports = Tree;

레퍼런스 풀이와 내 풀이를 비교 했을때 addchild에서 나는 너무 간단하게만 풀었던거 같아 문제 접근을 할때 여러 안될 조건을 생각 해야할거 같다. 그리고 reduce로 문제를 풀 생각을 못했는데 reduce로도 다시 풀어 봐야 할거 같다.

profile
어제보다 오늘 더 노력하는 프론트엔드 개발자

0개의 댓글