early return이란 무엇인가?
중첩되는 조건문들을 막고 가독성이 높은 코드를 구현하기 위해 사용됨.
왜쓰는가?
1. 중첩된 조건문은 가독성이 좋지 않다.
2. if부분이 길게되면 오류처리할 때 혼란스러움.
3. else부분에서 예외가 나타남.
BinarySearchTree.prototype.insert = function (value) {
const newNode = new BinarySearchTree(value);
if (this.value > value) {
if (this.left == null) {
this.left = newNode;
} else {
this.left.insert(value);
}
} else { //root.value와 파라미터로 입력된 value의 값이 같을 때는 추가되면 안되는데
//추가됨.
if (this.right == null) {
this.right = newNode;
} else {
this.right.insert(value);
}
}
};
-----------------------------------------------------------
BinarySearchTree.prototype.insert = function (value) {
if (this.value > value) {
if (this.left == null) {
this.left = new BinarySearchTree(value);
} else {
this.left.insert(value);
}
}
if (this.value < value) {
if (this.right == null) {
this.right = new BinarySearchTree(value);
} else {
this.right.insert(value);
}
}
};
코드로 구현하기전 나의 생각을 논리적으로 정리한 다음 코드로 옮겨써야함.
'javascript' 카테고리의 다른 글
| Prototype method vs Object method (0) | 2022.02.27 |
|---|---|
| if..else / if.. else if (0) | 2022.02.27 |
| Tree / Binary Search Tree (0) | 2022.02.26 |
| this (0) | 2022.02.16 |
| prototype/__proto__ (0) | 2022.02.05 |