이전 시리즈 글 : 코드 최적화 - 1. this.~ 문의 사용 보러가기
개요
- 시리즈 1편 개요와 동일함.
- 이하에서는 특정 값의 유효성을 검사하기 위한 코드인 ①if문 ②filter문을 정리함.
1. if 문
- if문으로 유효성 검사 이유
- 특정 객체가 undefined 또는 null 이 아닐 때만 코드 실행함
- 따라서 예기치 못한 오류 방지하여 코드 안정성을 높이기 위해 수행
- 예시 코드
// 예시 1
if (!this._detector) {
this._createDetector().then(detector => {
this._detector = detector;
console.log("model loading success!, detector: ", this._detector);
})
}
// 예시 2
if (!canvas || !this.isExistContent(this._result)) return canvas;
// 예시 3
if (this._result) {
this._result.forEach( (res) => {
ctx.fillStyle = res.handedness === "Left" ? "Red" : "Blue";
ctx.strokeStyle = "White";
ctx.lineWidth = 2;
res.keypoints.forEach(keypoint => {
this._drawKeypoint(ctx, keypoint);
});
Object.keys(FINGER_INDICES).forEach(finger => {
const points = FINGER_INDICES[finger].map(idx => res.keypoints[idx]);
this._drawPath(ctx, points, false);
});
});
}
2. filter문
- filter문으로 유효성 검사 이유
- 배열에서 특정 조건을 만족하는 값만 필터링
- filter 문은 배열에서만 사용 가능
- 예시 코드
const numbers = [1, 2, 3, 4, 5];
// 홀수만 필터링
const oddNumbers = numbers.filter(num => num % 2 !== 0);
console.log(oddNumbers); // 출력: [1, 3, 5]
'Backend > Node.js' 카테고리의 다른 글
[Coding-Practice] 코드 최적화 - 4. 간결한 코드 작성 (1) | 2023.12.01 |
---|---|
[Coding-Practice] 코드 최적화 - 3. for문과 forEach문 (0) | 2023.11.30 |
[Coding-Practice] 코드 최적화 - 1. this.~ (1) | 2023.11.30 |
[Function] 프로젝트 내에서 함수 구분 (1) | 2023.11.30 |
[Class] 클래스 상속 (0) | 2023.11.30 |