2017-10-12 14 views
0

I이 너무 많이 닮았에 있기 때문에 재산Angular1/자바 스크립트 - 너 한테 조건을 개선

checkProjectType() { 
    if (this.projectType.labelKey === 'project_type.rent') { 
     return 'geographical_area' 
    } else if (this.projectType.labelKey === 'project_type.buying') { 
     return 'geographical_area' 
    } else { 
     return 'address' 
    } 
    } 

의 값에 따라 객체 projectType와 다른 값을 반환의 동일한 속성 labelKey를 확인이 조건 내가 Lodash 나 ECMAScript 2015를 사용하여 단순화 된 쓰기로 조건을 리팩터링/최적화 한 상태?

답변

1

나는 또한 if-else-if… 체인을 좋아한다, 그래서 더 읽기 변형을 선호하지 않습니다.

function checkProjectType() { 
    const defaultType = 'address'; 
    const key = this.projectType.labelKey; 
    let map = { 
     'project_type.rent': 'geographical_area', 
     'project_type.buying': 'geographical_area' 
    }; 

    return map[key] || defaultType; 
} 

map은 다른 곳에서 정의 할 수 있습니다.

1

X를 else로 설정하면 else가 나에게 잘못된 것이므로 한 줄로 단순화 할 수 있습니다. if (this.projectType.labelKey === 'project_type.rent'|| this.projectType .labelKey === 'project_type.buying')은 이미 읽기가 쉽습니다.

2

코드 당 조건을 줄이면됩니다.

checkProjectType() { 
     var labelKey = this.projectType.labelKey; 
     if (labelKey === 'project_type.rent' || labelKey === 'project_type.buying') { 
      return 'geographical_area'; 
     } 
     return 'address'; 
     } 

회원님이 lodash 여기 이것은 switch 문 사용 기록 될 수

1

하나의 대안 방법으로 수행 할 작업을 확인하십시오

switch (this.projectType.labelKey) { 
case 'project_type.rent': 
case 'project_type.buying': 
    return 'geographical_area'; 
default: 
    return 'address'; 
} 

을하지만 하나가에서 조금 잔인한 주장 할 수 이 경우. Lodash 또는 ECMAScript 2015는 여기에 대해 아무 것도하지 않습니다.

1

프로젝트 유형이 유형의 배열에 포함되어 있는지 확인하고 응답을 선택하기 위해 원을 사용할 수 있습니다 geographical_area를 생산하는 유형, 당신은 방법에서 그들을 리팩토링 할 수있는 경우

checkProjectType() { 
    return ['project_type.rent', 'project_type.buying'].includes(this.projectType) ? 'geographical_area' : 'address'; 
} 

을 (그리고 객체/클래스) :

const geoTypes = ['project_type.rent', 'project_type.buying']; 

checkProjectType() { 
    return geoTypes.includes(this.projectType) ? 'geographical_area' : 'address'; 
}