갈푸라떼
갈푸라떼는 개발중
갈푸라떼
전체 방문자
오늘
어제
  • 분류 전체보기 (232)
    • CS (0)
      • CSinfo (0)
    • Frontend (15)
      • HTML,CSS (1)
      • Javascript (2)
      • React (0)
      • React Hook (12)
    • Backend (0)
      • Python (0)
      • Node.js (0)
      • php (0)
    • DB (2)
      • MySQL (2)
      • BigQuery (0)
      • Mongodb (0)
    • Study (186)
      • JavaScript (72)
      • JavaScript(Clean code) (50)
      • Node.js (11)
      • HTML,CSS (13)
      • React (30)
      • TypeScript (10)
      • React-Native (0)
    • Error (2)
      • error (2)
    • Git (22)
      • Git (22)
    • Help Coding (4)
      • Useful websites (3)

블로그 메뉴

  • 홈
  • 태그
  • 방명록
  • Github

공지사항

인기 글

태그

  • 렉시컬 환경
  • 심볼
  • function
  • 오버라이딩
  • PM2
  • Babel
  • 실행 컨텍스트
  • structure
  • SPREAD
  • 함수
  • 정적 레벨
  • 네이밍
  • nodemon
  • 컴파일러
  • this
  • Arrow
  • 싱글스레드
  • 인터프리터
  • 이터러블
  • 호이스팅
  • 원시타입
  • class
  • 상속
  • prototype
  • 프로토타입
  • 자바스크립트엔진
  • 객체타입
  • symbol
  • ECMAScript
  • 스코프 체인

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
갈푸라떼

갈푸라떼는 개발중

Study/JavaScript(Clean code)

[JavaScript][clean-code] for문 배열 고차 함수로 리팩터링 & 배열 메서드 체이닝

2022. 6. 5. 02:41

* for문 배열 고차 함수로 리팩터링

- 변수 다루기

- 임시변수 줄이기

 

* 예시로 보기

  • 아래의 패턴처럼 사용하는 부분이 많이 있을 것이다.
    • 임시변수를 만들어주고 for문을 이용해 임시변수에 값을 넣어주는 패턴
  • 이럴때는 배열 고차함수를 활용해서 배열문을 조금 더 선언적으로 명시적으로 변경할 수 있다.
const price = ['2000', '1000', '3000', '5000', '4000'];

function getWonPrice(priceList) {
  let temp = [];

  for (let i = 0; i < priceList.length; i++) {
    temp.push(priceList[i] + '원');
  }

  return temp;
}

- 해당 함수는 배열을 조작하는 함수로써 목록을 받아서 suffix를 붙여서 반환해주는 함수이다.

 

* 어떻게 리팩터링하면 좋을까?

  • 고차함수 map을 이용해 리팩터링 할 수 있따.
  • 불필요한 임시변수가 많이 줄어든다.
  • 결과는 동일하게 반환된다.
  • 그리고 추가 요구사항이 생길 경우 좀 더 명시적으로 코드를 추가할 수 있다.
    • ex) 1000원 초과 리스트만 출력, 가격 순 정렬
const price = ['2000', '1000', '3000', '5000', '4000'];

function getWonPrice(priceList) {
  return price.map((price) => price + '원');
}

const result = getWonPrice(price);
console.log(result);

* 추가 요구사항을 처리한 코드

const price = ['2000', '1000', '3000', '5000', '4000'];

const suffixWon = (price) => price + '원' // 원화로 변경
const isOverOneThousand = (price) => Number(price) > 1000 // 1000원 초과 리스트
const ascendingList = (a, b) => a - b; // 오름차순

function getWonPrice(priceList) {
  const isOverList = priceList.filter(isOverOneThousand)
  const sortList = isOverList.sort(ascendingList);

  return sortList.map(suffixWon);
}

const result = getWonPrice(price);
console.log(result);

* 배열 메서드 체이닝을 이용한 좀 더 명확한 코드 (배열 메서드 체이닝 활용)

const price = ['2000', '1000', '3000', '5000', '4000'];

const suffixWon = (price) => price + '원' // 원화로 변경
const isOverOneThousand = (price) => Number(price) > 1000 // 1000원 초과 리스트
const ascendingList = (a, b) => a - b; // 오름차순

function getWonPrice(priceList) {
  return priceList
    .filter(isOverOneThousand) // filter 원하는 조건에 맞는 배열 리스트 만들기
    .sort(ascendingList) // sort 정렬
    .map(suffixWon); // map 배열 요소들을 다시 정리
}

const result = getWonPrice(price);
console.log(result);

1.filter 2.array sort 3.map

  • 명확하게 사용가능
  • for반복문 if문을 사용하기 보단 고차함수를 이용하는것이 더 좋다.
  • 더 명확하고 더 선언적이다.
  • 체이닝을 이용하면 조금 더 명확한 파이프라인 처럼 보인다.

* 만약 위의 코드를 고차함수를 사용하지 않는다면??

const price = ['2000', '1000', '3000', '5000', '4000'];

function getWonPrice(priceList, orderType) {
  let temp = [];

  for (let i = 0; i < priceList.length; i++) {
    if (priceList[i] > 1000) {
      temp.push(priceList[i] + '원')
    }
  }

  if (orderType === 'ASCENDING') {
    someAscendingSortFunc(temp);
  }

  if (orderType === 'DESCENDING') {
    someDescendingSortFunc(temp);
  }

  return temp;
}
  • 결국 로직들이 늘어날수 있다는 아쉬움이 있다.
  • 굉장히 복잡해질 수 있다.

'Study > JavaScript(Clean code)' 카테고리의 다른 글

[JavaScript][clean-code] Continue & Break  (0) 2022.06.05
[JavaScript][clean-code] map vs forEach  (0) 2022.06.05
[JavaScript][clean-code] 불변성 (immutable)  (0) 2022.06.03
[JavaScript][clean-code] 유사 배열 객체  (0) 2022.06.03
[JavaScript][clean-code] 배열 요소에 접근하기(구조 분해 할당)  (0) 2022.06.01
    'Study/JavaScript(Clean code)' 카테고리의 다른 글
    • [JavaScript][clean-code] Continue & Break
    • [JavaScript][clean-code] map vs forEach
    • [JavaScript][clean-code] 불변성 (immutable)
    • [JavaScript][clean-code] 유사 배열 객체
    갈푸라떼
    갈푸라떼

    티스토리툴바